c - 学习动态内存分配

标签 c dynamic-memory-allocation

我是一名学生,我尝试自学代码。 我的问题:

我有两个结构:

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/

相关文章:

调用 C 风格的 DLL 成功,然后 AutoIt 崩溃

c++ - 按位运算符计算校验和

c - 如何防止数组冲突?

c - 为什么要使用 _mm_malloc? (相对于 _aligned_malloc、alligned_alloc 或 posix_memalign)

c - 这个 Valgrind 警告是什么意思? - 警告设置地址范围权限

c结构数组初始化

c - 从 C 程序运行查找以打印给定 inode 编号的文件名?

C++ - 字符串容量模式

c++ - Pimpl 成语内存使用

c++ - 在另一个结构中释放一个结构内的指针