Overview Pointer Variables Pass by Value Pass by
Overview • Pointer Variables • Pass by Value • Pass by Reference (or by Pointer) • Arrays
Pointers in C • Declaration int *p; /* p is a pointer to an int */ • A pointer in C is always a pointer to a particular data type: int*, double*, char*, etc. • Operators *p -- returns the value pointed to by p &z -- returns the address of variable z
Declaring Pointer variables int *ptr; ptr is a pointer variable that points to an int variable char *cp; cp is a pointer variable that points to a character variable double dp is a pointer variable that points to a double variable *dp; * is referred to as the indirection operator, or the dereference operator
Address Operator & int object; int *ptr; object = 4; ptr = &object ptr = null pointer variable ptr points to variable object pointer not = 0
Example Define local variables: int object; int *ptr; Now, let’s assign values to them: object = 4; ptr = &object *ptr = *ptr + 1; The last statement is equivalent to: object = object + 1
Example: Parameter Passing by Value #include <stdio. h> void Swap(int first. Val, int second. Val); int main() { int value. A = 3; int value. B = 4; Swap(value. A, value. B); return 0; } void Swap(int first. Val, int second. Val) { int temp. Val; /* Holds first. Val when swapping */ temp. Val = first. Val; first. Val = second. Val; second. Val = temp. Val; return; } Snapshot before return from subroutine
Example: Parameter Passing by Reference #include <stdio. h> void New. Swap(int *first. Val, int *second. Val); int main() { int value. A = 3; int value. B = 4; New. Swap(&value. A, &value. B); return 0; } void New. Swap(int *first. Val, int *second. Val) { int temp. Val; /* Holds first. Val when swapping */ temp. Val = *first. Val; *first. Val = *second. Val; *second. Val = temp. Val; return; } Snapshots during the exchange
Scanf( ) function • Recall reading from the keyboard in C: scanf(“%d”, &input); • Why do we use &input ?
Pointer Example #include <stdio. h> int Int. Divide(int x, int y, int *quo. Ptr, int *rem. Ptr); int main() { int dividend; int divisor; int quotient; int remainder; int error; /* /* /* The number to be divided The number to divide by Integer result of division Integer remainder of division Did something go wrong? */ */ */ printf("Input dividend: "); scanf("%d", ÷nd); printf("Input divisor: "); scanf("%d", &divisor); error = Int. Divide(dividend, divisor, "ient, &remainder); if (!error) /* !error indicates no error */ printf("Answer: %d remainder %dn", quotient, remainder); else printf("Int. Divide failed. n"); } int Int. Divide(int x, int y, int *quo. Ptr, int *rem. Ptr) { if (y != 0) { *quo. Ptr = x / y; /* Modify *quo. Ptr */ *rem. Ptr = x % y; /* Modify *rem. Ptr */ return 0; } else return -1; }
- Slides: 9