I have a struct and it has variables in it. Now I need to allocate memory dynamically, so initially I use
Struct struct-name *a =Null;
Latter on , I will allocate memory to it using malloc
,then I use
a[0].variableA=allocate , a[0].variableB=allocate.
My question is , is this even a pointer to struct, because no where I give the address of struct . And moreover this technique works , how does it know the address of struct . When I'm not explicitly giving address of struct using '&'. I know this might be silly but I got confused .Thanks .
Struct st
{
int a ;
int b;
}
Struct a *ptr=NULL;
In main
ptr=malloc(sizeof(struct st)*2);
//Assume array of size 2 is created
Now I can use
ptr[0].a=10;
How can I use even without explicitly giving address of struct to it.
The thing is you are not getting how malloc
works. (You mentioned I will allocate memory to it using malloc )
struct struct_name *a = NULL;
a = malloc(sizeof *a);
...
This computes the number of bytes that a struct struct_name
occupy in memory, then requests that many bytes from malloc
and assigns the result (ie, the starting address of the memory chunk that was just created using malloc
) to a pointer named a
. That is the whole story.
Now you will access it after making it sure that it didn't return NULL
. No need to apply &
address of to any struct struct_name
variable instance.
In your case, ptr
is used to access the different struct instance allocated dynamically - where is the address? The address pointing to the first instance is contained in ptr
. Then you used ptr[0]
or ptr[1]
to get to that structure instance. And then you accessed it.
And yes
ptr
is a pointer to struct.
One extra thing:-
malloc
may not be able to service the request, it may return a null pointer. It is good to check for this to prevent later attempts to dereference the null pointer. If you dereference a NULL pointer then it's undefined behavior.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.