C Pointers: Systems Programming
C Pointers: Systems Programming
C Pointers: Systems Programming
Systems Programming
Pointers
Reference
Swap – A Pointer Example
$./ptr1
i = 4, address of i = 3220392980
i = 4;
ptr = &i;
printf(" i = %d\n address of i = %u\n address of pointer = %u\n",
i, ptr, &ptr);
return 0; ./ptr2
} i=4
address of i = 3219352564
address of pointer = 3219352560
Systems Programming: Pointers 7
Pointers
/* Do you think in Hex ?*/ ptr
int main ()
{ bfe07240 bfe07244
int i; bfe07244 4
int *ptr;
i = 4; i
ptr = &i;
printf(" i = %d\n address of i = %p\n address of pointer = %p\n",
i, ptr, &ptr);
return 0;
./ptr3
}
i=4
address of i = 0xbfe07244
address of pointer = 0xbfe07240
Systems Programming: Pointers 8
Pointers
/* Never trust a Compiler. */
int j, i; /* think globally! */
int *ptr1, *ptr2; ptr1 8049654
void printit ()
{
ptr2 804964c
printf(" i = %2d, ptr1 = %p\n", i, ptr1);
printf(" j = %2d, ptr2 = %p\n", j, ptr2);
}
int main () j 19
8
9
{
i = 4; j = 8; i 4
6
ptr1 = &i;
ptr2 = &j;
printit (); ./ptr4
*ptr2 = *ptr2 + 1;
ptr1 = ptr1 - 2; /* You cannot know i =this4,*/ptr1 = 0x8049654
printit (); j = 8, ptr2 = 0x804964c
i = 6;
*ptr1 = *ptr1 + 10; i = 4, ptr1 = 0x804964c
printit (); j = 9, ptr2 = 0x804964c
return 0;
} i = 6, ptr1 = 0x804964c
j = 19,Pointers
Systems Programming: ptr2 = 0x804964c 9
7.4 Calling Functions by Reference
Call by reference with pointer arguments
– Pass address of argument using & operator
– Allows you to change the actual location in memory
– Arrays are not passed with & because the array
name is already a pointer.
* operator
– Used as alias/nickname for variable inside of function
void double( int *number )
{
*number = 2 * ( *number );
}
– *number used as nickname for the variable passed.
temp = *i;
*i = *j;
*j = temp;
}
mem1 = 12;
mem2 = 81;
swap (&mem1, &mem2); /* swap two integers */
printf("mem1:%4d mem2:%4d\n", mem1, mem2);
printf("\n");
return 0;
}
mem1: 30 mem2: 20
ray1[0] = 0 ray1[1] = 10 ray1[2] = 12 ray1[3] = 81
r 1 1 1 0 0 0
r 83 1 33 0 0 0
r 83 6 33 7 83 0
*ptr3++;
printf (" %f %f %f\n", x, y, z);
printf (" %u %u %u\n", ptr1, ptr2, ptr3);
printf (" %f %f %f\n", *ptr1, *ptr2, *ptr3);
(*ptr1)++;
printf (" %f %f %f\n", *ptr1, *ptr2, *ptr3);
--*ptr2;
printf (" %f %f %f\n", *ptr1, *ptr2, *ptr3);
return 0;
}