I'm tasked to create a program which dynamically allocates memory for a structure. normally we would use
x=malloc(sizeof(int)*y);
However, what do I use for a structure variable? I don't think its possible to do
struct st x = malloc(sizeof(struct));
Could someone help me out? Thanks!
person * myperson = (person *) malloc(sizeof(person)); This tells the compiler that we want to dynamically allocate just enough to hold a person struct in memory and then return a pointer of type person to the newly allocated data. The memory allocation function malloc() reserves the specified memory space.
Allocation and deallocation are done by the compiler. It uses a data structures stack for static memory allocation.
In the case of a Structure, there is a specific memory location for every input data member. Thus, it can store multiple values of the various members. In the case of a Union, there is an allocation of only one shared memory for all the input data members. Thus, it stores one value at a time for all of its members.
C malloc() method The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
My favorite:
#include <stdlib.h>
struct st *x = malloc(sizeof *x);
Note that:
x
must be a pointerYou're not quite doing that right. struct st x
is a structure, not a pointer. It's fine if you want to allocate one on the stack. For allocating on the heap, struct st * x = malloc(sizeof(struct st));
.
struct st* x = malloc( sizeof( struct st ));
It's exactly possible to do that - and is the correct way
Assuming you meant to type
struct st *x = malloc(sizeof(struct st));
ps. You have to do sizeof(struct) even when you know the size of all the contents because the compiler may pad out the struct so that memebers are aligned.
struct tm {
int x;
char y;
}
might have a different size to
struct tm {
char y;
int x;
}
This should do:
struct st *x = malloc(sizeof *x);
struct st *x = (struct st *)malloc(sizeof(struct st));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With