Tuesday, July 14, 2009

Using pointers in data structures in C?

If I create a data structure (in C) with a pointer in it, then a pointer of that structure's type:





struct data {


int a;


int *ptr;


}





struct data *info;





How do I initialize that pointer? Specifically, I'm trying to use malloc to allocate storage space for the pointer to point to.





I tried all of these:


info.*ptr = (int *)malloc(sizeof(int)*4);


*info.*ptr = (int *)malloc(sizeof(int)*4);


info.ptr = (int *)malloc(sizeof(int)*4);


*info.ptr = (int *)malloc(sizeof(int)*4);





But nothing seems to work. What am I doing wrong?

Using pointers in data structures in C?
Since you declared info as a pointer you first need to allocate the memory for that object with:





info=(struct data *)malloc(sizeof(data));





then





info-%26gt;ptr=(int*)malloc(sizeof(int)*4);





This will basically create an array in ptr that can be referenced with info-%26gt;ptr[0], info-%26gt;ptr[1], etc.





Make sure you free both sets of allocated memory when you are done with it.





Note that (*info).ptr will also work to reference that item.


No comments:

Post a Comment