0
#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?

0

2 Answers 2

1

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 ;)

Sign up to request clarification or add additional context in comments.

4 Comments

1. 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?
he's assigning string literals to non-const char *.
That's perfectly legitimate, even in "real code". What if you have to deal with one of the (many many many) APIs that don't have const correctness in their interfaces? Better to have a simple char * and avoid casting in a thousand places in your code.
@Asap - 1) 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 :)
0

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

4 Comments

is it possible if i make changes to p1.a1 and that changes are reflected in p.a1?
No, it's not. p1 and p are different objects. You can point both at the same string and modify that string, if that's what you want.
If i use this function strupr(p1.a1) it gives runtime error.But if i make char array in struct it does not why?
That's because you're trying to modify a string literal, which causes undefined behaviour. Don't do that. There are hundreds (seriously, go look) of questions about just that on this site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.