gpt4 book ai didi

c - 为什么我最后得到一个零,我怎样才能在不反转数组的情况下做同样的事情?

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:39 26 4
gpt4 key购买 nike

我是 C 的新手,只是试图理解一个问题的很小一部分我有一个简单的程序 -1 代表数组的末尾:

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

typedef struct List list_t;
struct List {
void * head;
list_t * tail;
};

list_t * makelist(void * x, list_t * xs){
list_t * ans = (list_t *) malloc(sizeof(list_t));
ans->head =x;
ans->tail = xs;
return ans;
}

list_t * makeListFromIntArray(int list[]){
list_t * ans = (list_t *) malloc(sizeof(list_t));
int i = 0;
while(list[i]!=-1){
ans = makelist((void *)(intptr_t)list[i],ans);
i++;
}
return ans;
}

void printList(list_t * xs){
while(xs != NULL){
printf("%lu\n",((intptr_t)xs->head));
xs = xs->tail;
}
}

int main() {
int s[] = {1,2,3,4,5,-1};
list_t * xs = makeListFromIntArray(s);
printList(xs);
return 0;
}

主要问题是当 printList 执行时我最后得到一个零。

5
4
3
2
1
0

Process returned 0 (0x0) execution time : 0.001 s
Press ENTER to continue.

这是我的主要问题,次要问题是数组颠倒了,这是可以理解的。在从 intarray 进入 makelist 之前,我可以通过反转来克服这个问题。但是我打开了更优雅的解决方案。

最佳答案

问题就在这里...

 list_t * ans = (list_t *) malloc(sizeof(list_t));

您正在 MakeListFromArray 中的列表头部创建一个空节点。该行应显示为

 list_t * ans = NULL;

附言:You should never cast malloc() in C!

关于c - 为什么我最后得到一个零,我怎样才能在不反转数组的情况下做同样的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15955667/

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