Рассмотрим следующий пример:
#include <stdio.h>
#include <stdlib.h>
struct Struct {
int a;
char name[20];
};
struct Struct struct1;
int main()
{
struct Struct *struct1_p;
struct1_p = &struct1;
struct1.a = 1;
printf("struct1->a = %d\n", struct1_p->a);
// Now let's create new structure dynamically
struct Struct * struct2 = malloc(sizeof(struct Struct));
// Now check if the allocation succeeded?
if(struct2 != NULL) {
//Success
//struct2 now is a pointer to the memory which is reserved for struct2.
struct2->a = 2;
} else {
// Allocation failed
}
printf("struct2->a = %d\n", struct2->a);
return 0;
}
Таким образом, имея тип нужного объекта, вы можете динамически создавать новый объект в памяти.Доступ к вновь созданному объекту через указатель, возвращаемый malloc
.Помните, что malloc возвращает void*
, нет необходимости явно приводить.