I have this program, which I want to understand the following output:
#include <stdio.h>
void fastSwap (char **i, char **d)
{
char *t = *d;
*d = *i;
*i = t;
}
int main ()
{
char num1[] = "hellohello";
char num2[] = "classclass";
fastSwap ((char**)&num1,(char**)&num2);
printf ("%s\n",num1);
printf ("%s\n",num2);
return 0;
}
The output will change only sizeof(void*) chars, instead of the entire array.
why does this happen?
&num1 is char**, isn’t it?
It’s
char (*)[11]. The fact that you casted tochar **clobbered the warnings of the compiler.What you are doing is thoroughly undefined behavior. You can’t make
num1point somewhere else because it doesn’t point anywhere to begin with: it’s an array, not a pointer.EDIT
As Paul R points out, here’s what is probably happening. The first
sizeof(char *)characters of each string are interpreted as a pointer and then those are swapped. What happens essentially depends on the size of the pointer on your implementation. It’s quite interesting, however I’m pretty sure it still qualifies as undefined.