Reputation: 2772
I was looking at a video lecture about how to do a generic swap using memcpy()
and strdup()
.
The generic swap code is as follows :
void GenericSwap(void* ptr1, void* ptr2, int size){
char buf[size];
memcpy(buf,ptr1,size);
memcpy(ptr1,ptr2,size);
memcpy(ptr2,buf,size);
}
and we call it like this :
char* h = strdup("fred");
char* w = strdup("wilma");
GenericSwap(&h,&w,sizeof(char*));
printf("h : %s\nw : %s\n\n",h,w);
This swapped "fred" and "wilma" as a whole string. That is, h points to "wilma" and w points to "fred" now.
However, when i change the code to this :
char h1[10] = "fred";
char w1[10] = "wilma";
GenericSwap(&h1,&w1,sizeof(char*));
printf("h1 : %s\nw1 : %s\n",h1,w1);
I get "wilm" and "freda" for h1
and w1
. I am passing address of stuff holding the address of the 1st element of the array, just like the proper working code up top, but this isn't working so nicely as the top one did.
Is it Something about h1
and w1
being mere pointers, and not pointer-to-pointers ?
Upvotes: 1
Views: 253
Reputation: 399803
You're trying to change the address of the arrays, which you cannot do. Array variables act as const
pointers to their data, they cannot be changed.
Instead, you're swapping the first sizeof (char *)
(which seems to be 4 on your system) characters.
Basically for
char h[8] = "foo";
The two statements
printf("%p\n", (void *) h);
and
printf("%p\n", (void *) &h);
will print the same address, i.e. the expression &h
evaluates to the address of the first element, just like h
. There is no separate variable that holds the array's address, for you to change.
Upvotes: 3