Functions & Pointers in C Jordan Erenrich [email protected].
-
Upload
julian-goodman -
Category
Documents
-
view
215 -
download
0
Transcript of Functions & Pointers in C Jordan Erenrich [email protected].
Functions
• Similar to Javafloat 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 <stdlib.h>
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
Memory Address~~~~ 0x0000~~~~ 0x0001
0x0002 ~~~~ 0x0002~~~~ .~~~~ .~~~~ .~~~~ .~~~~ 0xffff
Using Pointersint 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 pointervoid 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 memorychar myStr[50] = “Hello World”;
H e l l o w o r l d \0 ~ ~ ~
myStr
0x~~~
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 mallocchar *myStr;int length = 1234;myStr = malloc(sizeof(char)*length)
• Must explicitly de-allocate memoryfree(myStr);
Arrays of Arrayschar **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);