#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?
1) Struct p1 is a copy of p
2) HOWEVER - since a1 is a pointer, the copied pointers both point to the same memory. Until you reassign p1.a1 to the address of "vshaj".
3) Don't ever, ever do anything like this in real code ;)
p1.a1 and p.a1 are the same after the initialization of p1, but not after p1.a1 is reassigned. 2) What's wrong with this code?char *.const correctness in their interfaces? Better to have a simple char * and avoid casting in a thousand places in your code.p1=p;: These are two different objects, p1 is a copy of p; they occupy different memory. 2) Both p.a1 and p1.a1 initially point to the same memory object. So yes, they both point to the same memory object. Right up until p1.a1="vshaj";. 3) Bad things can happen if you try to modify the contents of either p.a1 or p1.a1, because the string you're pointing to is a read-only string literal. 'Hope that helps :)Yes, they do, until you reassign p1.a1, then of course they don't. 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
p1 and p are different objects. You can point both at the same string and modify that string, if that's what you want.