Docsity

Arrays, Strings, & Pointers, Summaries of Programming Languages

Partial preview of the text

Download Arrays, Strings, & Pointers and more Summaries Programming Languages in PDF only on Docsity!

Arrays, Strings, & Pointers

Alexander Nelson September 9, 2019

University of Arkansas - Department of Computer Science and Computer Engineering

Arrays, Strings, & Pointers

Arrays, Strings, & Pointers are all connected in C

  • Pointer – Variable storing a memory location
  • Array – Block of memory storing associated variables Array identifier is a pointer to location of first element
  • String – Array of character variables

Pointers

Pointers

Pointer – Variable that points to a memory location Requires:

  • Name – Name of the pointer variable
  • Type – Type of the variable that is being addressed, with appended asterisk e.g. int* myPointer; Variable size in memory is not based on type, but on memory size
  • Why?

Address of

Variable address accessed through ampersand (&) operator Literally the “address of” the variable Example:

int val = 5; int* myPtr = &val; //myPtr now is equal to memory location of val

Pointer Example

int val = 10; int* myPtr = &val; //declare pointer to val *myPtr = 5; //dereference pointer and set //that location = 5 printf("val =%d",val);//print val=(value of val)

Output =?

Arrays

Arrays

Array – “an ordered series or arrangement” C Array – Block of memory storing associated variables

  • Accessed by same variable name
  • Same data type

Example Arrays

double height[10];

  • type: double
  • name: height
  • length: 10 (memory size = 10×sizeof(double)) float width[30]; int c[9]; char name[20]; //string array

Array Implementation

Array identifier stores address of first element Array identifier dereferenced by bracket operator obtains value

1st element stored at position 0, 2nd at 1, nth at (n-1)th element e.g. a[n] = (n+1)th element

Accessing Array Elements

Accessed with a dereference operator and offset with [] operator Can be read & modified like a normal variable

Valid Examples:

  • c[0] = 3;
  • c[3] += 5;
  • y = c[x+1];

Multidimensional Arrays

Multidimensional arrays declared with each dimension e.g. int array[3][2];

Initialize each column through comma separated curly brace statements e.g. int array[3][2] = {{1,2},{3,4},{5,6}};

Memory-wise, the above is equivalent to: int array[6] = {1,2,3,4,5,6}

Passing Arrays to Functions

Array identifier = pointer to first element Identifier (memory address) is passed by value = reference to array

Array elements may be accessed by offset (known type) Length of array is not known! Use delimiter or pass length parameter(s)

Passing Array Elements

Array elements are passed by value! Original memory location will not be modified Example:

void myFunction(int a){ a = a+1; return a; } int main(){ int array[5] = {0}; myFunction(array[0]); printf("%d",array[0]); //Will print 0! }