[英]C Programming - Struct
#include<stdio.h>
struct s {
char *a1;
int a;
};
int main(){
struct s p={"asdv",11};
struct s p1=p;
p1.a1="vshaj";
printf("%d %s",p.a,p.a1);
}
In above program Does p1.a1 and p.a1 point to same memory address? 在上面的程序中,p1.a1和p.a1是否指向相同的存储器地址?
1) Struct p1 is a copy of p 1)结构p1是p的副本
2) HOWEVER - since a1 is a pointer, the copied pointers both point to the same memory. 2)但是-由于a1是一个指针,所以复制的指针都指向同一内存。 Until you reassign p1.a1 to the address of "vshaj". 直到将p1.a1重新分配给“ vshaj”的地址。
3) Don't ever, ever do anything like this in real code ;) 3)永远不要在真实代码中做这样的事情;)
Yes, they do, until you reassign p1.a1
, then of course they don't. 是的,他们会这样做,直到您重新分配p1.a1
,然后他们才不会。 You could just print them out to prove it. 您可以将它们打印出来以证明这一点。
Example code: 示例代码:
#include <stdio.h>
struct s
{
char *a1;
int a;
};
int main(void)
{
struct s p = { "asdv", 11 };
struct s p1 = p;
printf("They're the same: %p %p\n", p.a1, p1.a1);
p1.a1 = "vshaj";
printf("%d %s\n",p.a,p.a1);
printf("They're different: %p %p\n", p.a1, p1.a1);
return 0;
}
Example run: 举例来看:
$ make example
cc example.c -o example
$ ./example
They're the same: 0x10e258f2a 0x10e258f2a
11 asdv
They're different: 0x10e258f2a 0x10e258f48
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.