我是一名学生,我尝试自学代码。 我的问题:
我有两个结构:
struct1{
int a;
char name[20];}
struct 2{
struct struct1 *objekt;
int number;
double dNumber;}
我想动态分配内存,以便创建至少一个新的对象(由于缺乏更好的词)。例如,我知道我可以使用 malloc 或 calloc 分配内存。这很好。但是,如何在不定义新结构的情况下通过控制台输入动态添加新对象呢?我是一个完全的新手,很抱歉。谢谢。
最佳答案
考虑以下示例:
#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*
,无需显式转换。
关于c - 学习动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53485151/