Download presentation
Presentation is loading. Please wait.
1
Functions & Pointers in C Jordan Erenrich erenrich@cs.cornell.edu
2
Functions Similar to Java float multiply(float a, float b) { float ans = a * b; reutrn ans; }
3
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; }
4
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
5
What is a pointer? A reference to a physical memory address
6
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 );
7
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” */
8
C array implementation Pointer to a contiguous block of memory char myStr[50] = “ Hello World ” ;
9
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
10
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);
11
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);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.