A
arnuld
Excellent! It words the same with a pointer -- provided you think
about the value of the pointer itself
okay, you mean pointers are passed by copying. I have cooked a little
program to understand it:
#include <stdio.h>
enum { ARRSIZE = 2 };
void swap_ptr( int*, int* );
int main( void )
{
int x, y;
int *px, *py;
x = 1;
y = -1;
px = &x;
py = &y;
printf("px = %p, *px = %d\t", (void*)px, *px);
printf("py = %p, *py = %d\n", (void*)py, *py);
swap_ptr( px, py );
printf("px = %p, *px = %d\t", (void*)px, *px);
printf("py = %p, *py = %d\n", (void*)py, *py);
return 0;
}
void swap_ptr( int* pa, int* pb )
{
int* temp;
temp = pa;
pa = pb;
pb = temp;
}
================= OUTPUT ========================
[arnuld@dune ztest]$ gcc -ansi -pedantic -Wall -Wextra test.c
[arnuld@dune ztest]$ ./a.out
px = 0xbff5b244, *px = 1 py = 0xbff5b240, *py = -1
px = 0xbff5b244, *px = 1 py = 0xbff5b240, *py = -1
[arnuld@dune ztest]
you see, pointers are not getting swapped. It means, *everything* in C is
passed as a copy, rather than a reference. Even arrays are not exception
because they should be passed as a copy but the gist of C is that when you
pass an array , C silently passes a pointer to the first element of the
array which can change the original array elements. The pointer himself is
passed as copy. If you want to change the pointer itself, then you need
to pass a pointer to this pointer. I don't think I ever read this in any C
book, purely practical experience
Am I right ?