C 为什么';printf函数是否打印我想要打印的列表的值?

C 为什么';printf函数是否打印我想要打印的列表的值?,c,list,printf,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:

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

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

}


当我运行程序时,不会打印任何内容。

当您得到一个类似

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

}
#包括
#包括
类型定义结构S_节点{
int数据;
结构S_节点*下一步;
}节点;
int main(){
node*first=malloc(sizeof(node));
第一->数据=7;
first->next=NULL;
printf(“\n数据:%d”,第一个->数据);
}

第一个
未被分配(或初始化)正确的值。请阅读修订后的代码中唯一的问题是(
当前节点=!NULL){
行,您正在将
1
!NULL
)分配给
当前节点
,并获得类型不匹配(分配给指针的整数,在我的64位机器上大小不同)。这可能意味着:
while(currentNode!=NULL){
。当修复并运行时,它会产生一致的输出,但您应该在打印中的某个位置包含换行符(可能在
打印列表()
格式字符串的末尾)。谢谢,这使它工作起来,直到我决定为第二个节点分配内存,然后当我更改first->next=second时,给了我一个警告“从不兼容的指针类型分配”。要使第一个节点的下一个变量指向第二个节点,我必须做些什么?不客气,这就是结构S_node next和node first之间的区别。请检查此项。此代码唯一的答案将从一些解释中受益匪浅。阅读注释:注释中有解释。使用:
node*first=malloc(sizeof(*first));
等等。初始化为NULL后只调用
malloc()
@n.m]一行覆盖它是没有好处的。我想你和abelenky是在说错话。答案中代码中的
//C99
注释是答案的一部分。答案下面的注释是答案的一部分(就像我正在键入的)不是答案的一部分。我不清楚为什么你认为答案代码中的注释不是答案的一部分。我也更喜欢运行文本注释,但完全不同意答案代码中的注释是不合适的。@JonathanLeffler yeah误解了“注释”完全抱歉。代码中的注释是可以的,但我还是太简洁了,在这种情况下没有用处。
second->next = third;
node* first
#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

}