Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

seeking a clarification on structs

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
i have a doubts,
in c we can assign one structure variable to another
example

typedef struct
{
int i;
}test;

test a;
a.i=1;
test b=a;

this is a case of simple bit copying

now what happens when the elements of a structure are pointers
or that it allocates memory. Is it that same piece of memory would be allocated twice or released twice?
 
If the member of the structure is pointer and you do the same assignment, then the pointers in two structure variables will point to the same location. Because the address in the one pointer member will be copied to the other.

If you remove the allocated memory pointed by pointer variable through one structure variable then the other structure members memory location also removed.

If you do programing like this then this is a bug. In this case you have to do separate memory allocation and deallocation for both the structure variables after the initialization.

for example;

struct Pointer
{
char *p;
}v1, v2;


int main()
{
v1.p = malloc(sizeof(char) * 10);
scanf("%s", v1.p); // give max. upto 9 characters.
v2 = v1;
printf("%s %s", v1.p, v2.p); the give characters will be printed two times.
free(v1.p);
scanf("%s", v2.p); //error the allocated memory is removed and will cause runtime errors like coredump.
printf("%s", v2.p);
return 0;
}
 
well i understand what you said but the doubt

i was wondering wheather c has some concept of default
copy construction as c++. this has more to do with
proper initialization than to do with structure instance

please suggest
 
with C you would need a function to do the copy

struct example{
char* p;
};

void copyStruct(struct example copyTo, struct example copyFrom)
{
copyTo.p = (char*)malloc(strlen(copyFrom.p) +1);
strcpy(copyTo.p,copyFrom.p);
}

Matt
 
Hi,

Running smaniraja's program produced no errors for me.

Enter the v1.p string: thisisv1p
thisisv1p thisisv1p

Enter the v2.p string: thisisv2p
thisisv2p

So, why does it work then? Is it that it got lucky and you would normally see an error here? I compiled it on UNIX.

Thanks.

-Tyler
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top