Functions & Pointers in C Jordan Erenrich
Functions Similar to Java float multiply(float a, float b) { float ans = a * b; reutrn ans; }
Forward References C compiler is one pass Functions must be declared before they are used. Typically: #include float multiply(float, float); /* Forward reference */ int main (int argc, char* argv[]) { int x, y, z; x = 5; y = 2; z = multiply(x, y); } float multiply(float a, float b) { return a*b; }
Passing by Value Function parameters are unchanged, outside of the function. i.e., void swap(float a, float b) { float temp; temp = a; a = b; b = temp } This function is useless How can we modify external data? Use pointers
What is a pointer? A reference to a physical memory address
Using Pointers int x = 42; int* iPtr; /* int* is a pointer type */ iPtr = &x; /* & gets a pointer to a variable */ /* Outputs “42 = 42” */ printf( “ %d = %d\n ”, x, *iPtr ); x = 137; /* Outputs “137 = 137” */ printf( “ %d = %d\n ”, x, *iPtr );
Passing by Reference Use the * operator to dereference a pointer void swap(float* a, float* b) { float temp; temp = *a; *a = *b; *b = temp } Therefore: int x = 42, y = 137; printf( “ %d - %d ”, x, y); /*Prints “42 –137” */ swap(&x, &y); printf( “ %d - %d ”, x, y); /*Prints “137 – 42” */
C array implementation Pointer to a contiguous block of memory char myStr[50] = “ Hello World ” ;
Declaring Arrays Static length is simplest #define MAXSTRING 1000 char myString[MAXSTRING] But, it’s size is…static Arrays can not be resized after a static declaration
Dynamically Allocation Arrays Explicitly allocate memory with malloc char *myStr; int length = 1234; myStr = malloc(sizeof(char)*length) Must explicitly de-allocate memory free(myStr);
Arrays of Arrays char **arrOfStrs; /*Double pointer*/ int i, strLen = 1024, numStrings = 5; /*Allocate the memory*/ arrOfStrs = malloc(sizeof(char*)*numStrings); for(i = 0; i < numStrings; i++) { arrOfStrs[i] = malloc(sizeof(char)*strLen); }... /*Free the memory*/ for(i = 0; i < numStrings; i++) { free(arrOfStrs[i]); } free(arrOfStrs);