gpt4 book ai didi

c - C中没有程序输出

转载 作者:行者123 更新时间:2023-11-30 20:45:31 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com