c语言 - 为什么 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;

当我运行程序时,没有打印任何内容。

当你得到像这样的指针时

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);
}
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
}

相关内容

最新更新