c - C中没有程序输出

标签 c

#include<stdio.h>
#include<malloc.h>

typedef struct node_t {
    int i;
    struct node_t* link;
} node;

node* head = NULL;

int main() {
    int i = 10;
    node* temp = NULL;
    head = (node *)malloc(sizeof(node));
    temp = (node *)malloc(sizeof(node));
    if(temp == NULL) {
        printf("\n malloc for temp node failed! \n");
    }
    else {
        /* linked list logic to add the elements in the beginning */
        while(i<=10) {
            temp->i = i;
            temp->link = NULL;
            if(head == NULL) {
                head = temp;
            }
            else {
                temp->link = head;
                head = temp;
            }
            i++;
        }
    }
    for(temp = head; temp->link != NULL; temp = temp->link) {
        printf("\n The data is:%d \n",temp->i);
    }
    free(temp);
    free(head);
    return 0;
}

我正在尝试一个简单的链表程序。我没有得到输出。

最佳答案

1) 每次为 tmp 赋值时,都必须分配节点 (tmp)。并且不只分配一次tmp。请参阅以下固定代码以了解如何操作

2) 下面的for循环是错误的:

for(temp = head; temp->link != NULL; temp = temp->link) {

for 循环已在以下代码中修复

3) 对于free,您必须浏览整个链表,然后释放每个节点。请参阅以下固定代码。

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

typedef struct node_t{
    int i;
     struct node_t* link;
}node;

node* head = NULL;

int main(){
     int i = 1;
     node* temp = NULL;

     /* linked list logic to add the elements in the beginning */
     while(i<=10){
         temp = (node *)malloc(sizeof(node));
         if(temp == NULL){
             printf("\n malloc for temp node failed! \n");
             exit(1);
         }
         temp->i = i;
         temp->link = NULL;
         if(head == NULL){
             head = temp;
         }
         else{
             temp->link = head;
             head = temp;
         }
         i++;
     }

     for(temp = head; temp != NULL; temp = temp->link){
         printf("\n The data is:%d \n",temp->i);
     }

     while (head!=NULL)
     {
        temp = head->link;
        free(head);
        head = temp;
     }

}

关于c - C中没有程序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621062/

相关文章:

c - 使用指针以相反顺序检索值

c - 读取文件并保存为矩阵

我可以将 C 内联函数桥接到 Swift 吗?

c - 原子结构的目的

c++ - 迷你过滤器无法阻止 'Windows Photos' 打开的图像

c - 从现有文件描述符分配一个结构体 - c

c - 是否可以将结构转换为另一个结构?

c - 在c中使用赋值语句for循环条件

c - X11:检测一般的鼠标和键盘事件

c - 是否不允许对操作的左值进行类型转换?