我正在嘗試創建一個 Product 結構陣列,然后列印陣列中每個 Product 的名稱和代碼,但我一直遇到分段錯誤。我試圖在沒有回圈的情況下插入每個值,然后列印,它可以作業,但我想自動化它。函式 fill_products 根據用戶的輸入填充 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;
}
uj5u.com熱心網友回復:
我不斷收到分段錯誤。
請啟用編譯器警告,并注意它們。
這段代碼:
char *name;
...
scanf("%s", &name);
是虛假的,根本沒有按照您的意愿行事。
您必須單獨分配空間name(然后不要忘記free()),或者使該空間在Product結構中可用,如下所示:
typedef struct
{
int code;
char name[100];
float price;
} Product;
(這假設有一個合理的name長度限制)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/444617.html
上一篇:通過函式列印陣列的內容
