c - restrict the pointers in structures -


struct {    int *p;    int c; } a1,a2;  void fun(struct a);  int main() {      a1.p=malloc(4);     *(a1.p)=10;     a1.c=20;      fun(a1);     printf("%d\n",*(a1.p));     return 0; }  void fun(struct temp) {        a2=temp;     *(a2.p)=30;     printf("%d\n",*(a2.p)); } 

i have program , question is.... when assign *(a2.p)=30; affects *(a1.p) value how avoid?i.e, though changed *(a2.p) value don't want affect *(a1.p) value how ypu it? please suggest me

thanks in advance

you need this:

a2.p = malloc( sizeof( int ) ); // << note this.  if ( a2.p == null ) {   // ran out of memory in memory pool. error handling. }  *( a2.p ) = 30; 

... note a1.p , a2.p both point same block of memory. hence, change a2.p points before mutating value.

aside:

  • do not malloc fixed size (your malloc( 4 ) should malloc( sizeof( int ) )).

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -