Reputation: 3
I'm a programming noob. I want to allocate a struct but since the size of my attributes are already defined, how would I use malloc() in this case?
Here is my struct:
typedef struct sc sc_t;
struct sc {
// Attributes
};
I've looked at several different examples but I'm still unsure if these examples entirely apply to me. Can this be accomplished by sc_t * sc_t_new = (sc_t *)malloc(sizeof(sc_t));
?
Upvotes: 0
Views: 525
Reputation: 58868
The question doesn't make sense. A struct is its members (what you called "attributes"). It's like asking how to make an omelette that doesn't contain eggs in a frying pan with no bottom on a stove with no burners.
More programming-related, it's like asking how to allocate an int
without any digits.
You just allocate a struct and the struct has its members inside it already.
You can use:
sc_t * sc_t_new = malloc(sizeof(sc_t));
(the extra (sc_t*)
is not needed in C, only in C++)
You can also use:
sc_t * sc_t_new = malloc(sizeof(*sc_t_new));
which helps prevent you from making a mistake if you decide to change it to a different struct later.
For context to my nonsensical question, someone in my class asked the TA "Since the array attributes in our struct have a defined size and are not allocated on the heap, it's safe to only free the struct itself since it's the only thing allocated, correct?" and TA said that is correct.
Your classmate was probably confused about structs that contain pointers. If you have code like this:
struct S {
int *a;
};
struct S *s = malloc(sizeof(struct S));
s->a = malloc(sizeof(int)*100);
then the pointer variable a
is a member of the struct, but the array of 100 ints is not - that is completely separate from the struct!
If you did this:
free(s);
it would free the struct, but not the array. To free the struct and the array you would do this:
free(s->a);
free(s);
Pay attention: that's because the array is not a member in this case. Only the pointer to the array is a member.
Upvotes: 3
Reputation: 7726
Here's a good example:
#include <stdio.h>
#include <stdlib.h>
#define MAX_ELEMENTS 5
typedef struct {
char name[100];
} e_struct;
int main(void) {
// Allocating MAX_ELEMENTS number of elements of type 'e_struct'
e_struct *n = (e_struct *)malloc(sizeof(e_struct) * MAX_ELEMENTS);
// Some usage of *n then free the memory...
free(n);
return 0;
}
This line:
e_struct *n = (e_struct *)malloc(sizeof(e_struct) * MAX_ELEMENTS);
Will tell the compiler to allocate the memory for n
pointer of type e_struct
for MAX_ELEMENT
bytes times the size of the e_struct
in bytes (i.e. MAX_ELEMENTS * sizeof(e_struct)
:
+----------+----------+----------+----------+----------+
| ELEM1 | ELEM2 | ELEM3 | ELEM4 | ELEM5 |
+----------+----------+----------+----------+----------+
|name[100] | name[100]| name[100]| name[100]| name[100]|
+----------+----------+----------+----------+----------+
Upvotes: 0