首页 文章

如何将内存分配给C中结构中的char指针?

提问于
浏览
-2

我在下面使用这个结构,但如果我想从一个巨大的文件中获取所有String,它是有限的...

typedef struct arr {
    char name[200]; // Could be a number higher than 200 here...
} array;

现在,如果我用...

typedef struct arr {
    char *name;
} array;

那么,是否可以为struct(array)中的char指针(* name)分配内存?

我不知道我做错了什么,我为数组分配了内存,但不知怎的,我得到了一个Segmentation fault错误 . name[200] 的结构没有给我任何错误 . *name 的结构 .

array *str = malloc(sizeof(*str));

我错过了分配别的东西吗?

3 回答

  • 0

    我错过了分配别的东西吗?

    是 . 您在 array 内为 array 分配了内存,但没有为 name 分配内存 .

    你需要:

    array *str = malloc(sizeof(array));
    if ( str == NULL )
    {
       // Deal with the error
    }
    
    str->name = malloc(200);
    
  • 3

    当您明确编码所需的内存量时,您的第一个分配方法会为内存区域分配200个字符 . 您的第二个分配方法只会为组成指针分配空间 . 因此,首先分配结构,然后显式地为组成指针分配空间 .

    array *str = (array*)malloc(sizeof(array));
    int n = 200;
    str->name = (char*)malloc(sizeof(char)*n);
    
  • 0

    是的,您可以将内存分配给结构内的char指针

    array *str = (array *)malloc(sizeof(array));
    if ( str == NULL )
    {
       printf("Memory allocation failed \n")
       exit (0);
    }
    str->name = (char*)malloc(sizeof(char)*200);
    if (str->name)
    {
       printf("Memory allocation failed \n")
       exit (0);
    }
    ...
    //use free() to destroy the memory allocated after use.
    free(str->name);   //first destroy the memory for the variable inside the structure
    free(str);  //destroy the memory allocated to the object.
    

    比使用指针'* str'和'* name'后使用'free()'来破坏动态分配的内存 . 首先释放'* name'而不是'* str' .

相关问题