簡體   English   中英

為什么從此結構打印會出現分段錯誤?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM