简体   繁体   中英

My C program doesn`t work unless I add a printf before everything else

I tried to run the code and it terminates and doesn`t print anything, but if I include a printf statement as the first line in the main, it works. Why?

#include <stdio.h>
#include <stdlib.h>

typedef struct node TNode;
typedef struct list TList;

struct list{
    TNode *node;
};

struct node{
    int data;
    TNode *next;
};

TList* buildList(){
    TList *list;
    list = (TList*)malloc(sizeof(TList));
    list->node->next = NULL;
    printf("\nList was built successfully\n");
    return list;
}


int main(){
    TList *myList = buildList();
    myList->node->data = 5;
    printf("\nData: %d\n", myList->node->data);
    return 0;
}

You are accessing list->node->next without having initialized list->node . Allocate memory for the node and assign a pointer to it to list->node .

#include <stdio.h>
#include <stdlib.h>

typedef struct node TNode;
typedef struct list TList;

struct list{
    TNode *node;
};

struct node{
    int data;
    TNode *next;
};

TList* buildList(){
    TList *list;
    list = (TList*)malloc(sizeof(TList));
    list->node = (TNode*)malloc(sizeof(TNode));    // <---
    list->node->next = NULL;
    printf("\nList was built successfully\n");
    return list;
}


int main(){
    TList *myList = buildList();
    myList->node->data = 5;
    printf("\nData: %d\n", myList->node->data);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM