How to allocate dynamic memory for structure in my code
I know how to use malloc to allocate dynamic memory
Code:
int *ptr = (int *) malloc(4 * sizeof (int));
if (ptr == NULL) {
/* Memory could not be allocated
} else {
/* Allocation succeeded. Do something. */
free(ptr);
ptr = NULL; /* The pointed-to-data must not be used again,
unless re-assigned by using malloc
again. */
}
How to allocate dynamic memory for the structure in code ?
Code:
#include <stdio.h>struct Person
{ int N; float height; }p1;
void show_person(struct Person p) {
printf( "person %d is %f meters tall.\n", p.N, p.height );
}
void change_height(struct Person *p, float new_height) {
p->height = new_height;
}
int main(void) {
p1.N = 1;
p1.height = 2.0;
show_person(p1);
change_height(&p1, 1.9) ;
show_person(p1);
return 0;
}