【问题标题】:Allocate memory for struct array element (string)为结构数组元素(字符串)分配内存
【发布时间】:2014-11-02 11:24:10
【问题描述】:

我正在尝试从键盘读取并将信息存储在我的结构书中。要求用户输入数组大小,然后我将大小动态分配给我的 book 数组。但是当 n > 1 时,运行时错误是 exc_bad_access。我不知道为什么它在 n = 1 时起作用,而在 n > 1 时不起作用。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct book
{
    char *title;
    char *author;
    double price;
};

int main()
{
    int n, i = 0;
    printf("please enter the value for n\n");
    scanf("%d", &n);

    struct book *stack = malloc(sizeof(struct book) * n);
    stack->author = malloc(sizeof(char) * 100);
    stack->title = malloc(sizeof(char) * 100);
    //allocate memory for book and struct members
    while (i < n )
    {
        printf("Please enter the title\n");
        scanf("%s", stack[i].title);
        printf("Please enter the author\n");
        scanf("%s", stack[i].author);
        printf("Please enter the price\n");
        scanf("%lf", &stack[i].price);
        i ++;
    }
    free(stack);
    return 0;
}

【问题讨论】:

  • sizeof (char) 是多余的,因为它是 1 每个定义。
  • 我这里的想法是可以设置输入的字符数上限,所以我认为有必要保持它对吗?
  • 使用带有%s 的长度说明符来防止缓冲区溢出。另外,如果书名或作者姓名中有多个单词,您可能需要重新考虑输入法的选择!
  • sizeof (char) * 100 等于 1 * 100 等于 100。那么使用sizeof (char)有什么必要呢?编码100 就可以了。

标签: c arrays string memory struct


【解决方案1】:

您为输入的任何大小的元素分配了足够的结构,但没有为缓冲区分配空间

struct book *stack = malloc(sizeof(struct book) * n);
stack->author = malloc(sizeof(char) * 100);
stack->title = malloc(sizeof(char) * 100);
// what about stack[1].author, stack[2].author and the rest??

这将起作用:

struct book *stack = malloc(sizeof(struct book) * n);
for (int i = 0; i < n; ++i) {
    stack[i].author = malloc(sizeof(char) * 100);
    stack[i].title = malloc(sizeof(char) * 100);
}

记住也要释放你的记忆。

【讨论】:

  • 在 C 中,malloc/calloc/realloc 的结果不是必需的,也不推荐。只是不要这样做。
【解决方案2】:

对于堆栈中的每一本书,您必须为作者和标题分配内存。

for(int i = 0; i < n; i++)
{
    stack[i].author = malloc(sizeof(char) * 100);
    stack[i].title = malloc(sizeof(char) * 100);
}

您只是为第一个元素分配内存。

【讨论】:

  • stack->author = malloc(sizeof(char) * 100); stack->title = malloc(sizeof(char) * 100);
【解决方案3】:

你需要为

分配内存
char *title;
char *author;  

当您执行struct book *stack = malloc(sizeof(struct book) * n); 时,内存分配给char* 指针(4 或8 个字节,具体取决于您正在构建的平台)。

所以你需要为内部值分配一些内存

while (i < n )
{
    char *title = malloc(255 * sizeof(char));
    printf("Please enter the title\n");
    scanf("%s", title);
    stack[i].title = title;
    .....
    i ++;
}

【讨论】:

  • 为什么是中间title?为什么不直接分配并读入结构的成员?
猜你喜欢
  • 2022-11-28
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多