【发布时间】: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