[英]Confusion with pointer program (c programming)
When compiling this program I receive an output that I would've never expected. 编译该程序时,会收到我从未期望过的输出。 When I reviewed this program I expected the outcome of pointer to be still "Hello, world!"
当我查看该程序时,我希望指针的结果仍然是“ Hello,world!”。 because to my knowledge pointer was never affected by pointer2 .
因为据我所知指针从来没有受到指针2。 Yet, my output shows that when pointer is printed it contains pointer2 's string "y you guys!".
但是,我的输出显示,当指针被打印时,它包含pointer2的字符串“ y you guys!”。 How is this so??
怎么样了? Thanks!!
谢谢!!
#include <stdio.h>
#include <string.h>
int main() {
char str_a[20];
char *pointer;
char *pointer2;
strcpy(str_a, "Hello, world!\n");
pointer = str_a;
printf(pointer);
pointer2 = pointer + 2;
printf(pointer2);
strcpy(pointer2, "y you guys!\n");
printf(pointer);
}
Output 输出量
Hello, world!
llo, world!
Hey you guys!
You have a single area of memory, the array str_a
. 您只有一个内存区域,即数组
str_a
。
After strcpy
call and the assignments to pointer
and pointer2
is looks something like this in memory: 在
strcpy
调用之后, pointer
和pointer2
的分配在内存中看起来像这样:
+---+---+---+---+---+---+---+---+---+---+---+---+---+----+----+----------------------+ | H | e | l | l | o | , | | w | o | r | l | d | ! | \n | \0 | (uninitialized data) | +---+---+---+---+---+---+---+---+---+---+---+---+---+----+----+----------------------+ ^ ^ | | | pointer2 | pointer
The variable pointer
points to str_a[0]
and pointer2
points to str_a[2]
. 变量
pointer
指向str_a[0]
而pointer2
str_a[2]
指向str_a[2]
。
When you call strcpy
with pointer2
as the destination, you change the memory that pointer2
points to, which is the same array that pointer
also points to, just a couple of character further along. 当您以
pointer2
为目标调用strcpy
时,您将更改pointer
的内存,该内存与pointer
也指向的数组相同,仅pointer2
几个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.