#include <stdio.h> void Initialize (char * a, char * b) { a[0] = 'T'; a[1] = 'h'; a[2] = 'i'; a[3] = 's'; a[4] = ' '; a[5] = 'i'; a[6] = 's'; a[7] = ' '; a[8] = 'A'; a[9] = '\0'; b = a; b[8] = 'B'; } #define ARRAY_SIZE 10 char a[ARRAY_SIZE]; char b[ARRAY_SIZE]; int main(int argc, char * argv[]) { Initialize(a, b); printf("%s\n%s\n", a, b); return 0; }
When you run this program, only "This is B" is printed. To see why, place a
breakpoint in the line b[8] = 'B' and rerun the program. Take a look at the values
of a and b. They are the same, as they should be, because we assigned a to b in the
previous line. What is the same, however, is not the contents of the arrays but
the two arrays have the same address after the assignment b = a. The contents are
not only equal, they are the same. Modifying one will also modify the other. The
assignment b[8] = 'B' will modify the bits of memory that also contain a[8], and
the contents of the original b will remain untouched. The two original arrays
still get printed, but the first one will now contain "This is B" and the second
will be empty because it was never touched. The address of the second one, which
was allocated by the compiler when it was declared, was overwritten and discarded
by the line b = a before its contents were modified.