#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.
C语言指针与数组修改
本文通过一个C语言程序示例,详细解释了当一个数组被另一个变量指向时,修改其中一个如何影响另一个。并说明了在内存中,两个变量实际上指向同一地址,因此修改其中一个会同时影响到另一个。
3627

被折叠的 条评论
为什么被折叠?



