为什么printf函数不打印我要打印的列表的值?

时间:2018-11-17 16:33:52

标签: c list printf

我无法打印第一个节点的数据值。有人可以告诉我我在做什么错吗?

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


typedef struct S_node{

  int data;
  struct S_node *next;

} node;


int main () {

  node* first; 

  first->data = 7;
  first->next = NULL;

  printf("\nData: %d", first->data);

}

我更新了代码:

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


typedef struct S_node{

  int data;
  struct S_node *next;

} node;

void PrintList(node* start);

int main () {

  node* first = malloc(sizeof(node));
  node* second = malloc(sizeof(node));
  node* third = malloc(sizeof(node));

  first->data = 7;
  first->next = second;

  second->data = 6;
  second->next = third;

  third->data = 5;
  third->next = NULL;

  PrintList(first);

  free(first);
  free(second);
  free(third);
}

void PrintList(node* start) {

node* currentNode = start;
while(currentNode =! NULL) {
    printf("Data: %d", currentNode->data);
    currentNode = currentNode->next;
}
}

我正在尝试从第一个节点到最后一个节点打印数据,这样做时仍然收到“来自不兼容指针类型的赋值”警告

first->next = second;

second->next = third;

当我运行程序时,什么都没有打印出来。

2 个答案:

答案 0 :(得分:1)

当您获得类似

的指针时
node* first

您应专门将此指针指向哪个地址。 通过malloc,我们可以在内存中获得动态空间,并将地址分配给指针。

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


typedef struct S_node {

    int data;
    struct S_node *next;

} node;


int main() {

    node* first = malloc(sizeof(node));

    first->data = 7;
    first->next = NULL;

    printf("\nData: %d", first->data);

}

答案 1 :(得分:0)

int main () {

  node* first = NULL;           // Be Explicit that the pointer is not yet valid.
  first = malloc(sizeof(node)); // Now there is memory attached to the pointer.

  first->data = 7;
  first->next = NULL;

  printf("\nData: %d", first->data);

  free(first);  // Release the memory when done.
  first = NULL; // Prevent accidental re-use of free'd memory

}