[英]Why does printing from this struct give a segmentation fault?
我试图创建一个 Product 结构数组,然后打印数组中每个 Product 的名称和代码,但我一直遇到分段错误。 我试图在没有循环的情况下插入每个值然后打印,并且它有效,但我想自动化它。 function fill_products 根据用户输入填充产品数组,select_products 打印整个数组的每个名称代码对。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int code;
char *name;
float price;
} Product;
void select_products(Product *products, int len)
{
int i;
printf("%-30s%s\n", "Name", "Code");
for (i = 0; i < len; i++)
{
printf("%-30s%d\n", products[i].name, products[i].code);
}
return;
}
void fill_products(Product *products, int len)
{
int i, code;
char *name;
float price;
for (i = 0; i < len; i++)
{
printf("Insert product name (%d / %d): ", i + 1, len);
scanf("%s", &name);
printf("Insert product price (%d / %d): ", i + 1, len);
scanf("%f", &price);
products[i].code = i;
products[i].name = name;
products[i].price = price;
}
return;
}
int is_alloc(Product *products)
{
if (products == NULL)
{
printf("Error: memory allocation unsuccessful.\n");
}
return products != NULL;
}
int main(void)
{
int len, n_bytes;
Product *products;
printf("Insert length of array: ");
scanf("%d", &len);
n_bytes = sizeof *products * len;
products = malloc(n_bytes);
if(!is_alloc(products))
{
exit(0);
}
fill_products(products, len);
select_products(products, len);
free(products);
return 0;
}
我不断收到分段错误。
请启用编译器警告,并注意它们。
这段代码:
char *name;
...
scanf("%s", &name);
是假的,根本不做你想要的。
您必须为name
单独分配空间(然后不要忘记free()
它),或者使该空间在Product
结构中可用,如下所示:
typedef struct
{
int code;
char name[100];
float price;
} Product;
(这假设name
长度有一个合理的限制)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.