簡體   English   中英

將scanf值傳遞給struct pointer Segmentation Fault

[英]pass scanf value to struct pointer Segmentation Fault

我想要做的就是使用用戶輸入使用結構指針進行基本打印。 當我嘗試使用下面的代碼時,我遇到了segmentation fault 我是c的新手,不管怎樣,謝謝。

typedef struct {
    int *licenseNum;
    char *name;
    char *region;
} City;

typedef struct {
    struct Node *current;
    struct Node *head;
    struct Node *tail;
    struct Node *next;
    struct Node *secondNext;
    City *data;
} Node;


int main()
{
    Node *node = malloc(sizeof(Node));
    City *city = malloc(sizeof(City));
    puts("License number of the City: ");
    scanf("%d", &(node -> data -> licenseNum));
    printf("%d", node -> data -> licenseNum);
    return 0;
}

您沒有在node設置data

Node * node = malloc(sizeof(Node));
City * city = malloc(sizeof(City));
// node->data is not yet defined!
// It has a random value! You must first initialize it:
node->data = city;

此外,您不應在此處使用malloc ,因為malloc分配的malloc具有隨機值。 如果您確實在使用之前初始化struct具有有意義值的所有指針,請僅使用malloc 使用calloc更安全:

Node * node = calloc(1, sizeof(Node));
City * city = calloc(1, sizeof(City));
node->data = city;

calloc工作方式與malloc類似,但它保證返回的內存全部設置為零(所有int值都為0 ,所有指針都為NULL )。 calloc的第一個參數(上面代碼中的1 )是你想要分配的項目數,這里只是一個。 例如calloc(5, sizeof(City))將在一個塊中為5個城市分配內存,例如:

Cities * cities = calloc(5, sizeof(City));
cities[0].name = "New York";
cities[1].name = "London";
// ... and so on

您沒有初始化node->data

您為node分配了內存,但沒有為node->data分配內存。

你可能想這樣做: node->data = city

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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