c - c 创建两个新列表但得到错误的结果
问题描述
我正在用C创建两个新列表,代码如下所示
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList(int list[], int listsize){
struct ListNode *newlistnode;
struct ListNode *curlistnode;
struct ListNode *listhead;
for(int i = 0; i < listsize; i++){
newlistnode = (struct ListNode*) malloc(sizeof(struct ListNode));
newlistnode -> val = list[i];
newlistnode -> next = NULL;
if(listhead == NULL)
listhead = newlistnode;
else
curlistnode ->next = newlistnode;
curlistnode = newlistnode;
}
return listhead;
}
int main(){
int a[4] = {2, 4, 3};
int b[4] = {5, 6, 4};
int listsize = 3;
struct ListNode* list_a = createList(a, listsize);
struct ListNode* list_b = createList(b, listsize);
return 0;
}
这是我得到的:
list_a : 2->4->3->NULL
list_b: 2->4->3->5->6->4->NULL
我很困惑,谁能帮帮我?
解决方案
问题是您没有初始化函数体中的指针。如前所述,这是未定义的行为。
struct ListNode *newlistnode;
struct ListNode *curlistnode;
struct ListNode *listhead;
改成这个
struct ListNode *newlistnode = NULL, *curlistnode = NULL, *listhead = NULL;
推荐阅读
- c++ - c++ openmp 对对齐数组的错误共享示例
- javascript - 如何在javascript中计算数组对象的唯一值
- r - 计算子字符串中每个下一次出现的字符串
- postgresql - Pgsql如何从脚本返回一个值
- javascript - 如何在 3 个条件下使用三元运算符从 github api 获取数据?
- hyperledger-fabric - 如何从 Hyperledger Composer 中的事务返回查询结果
- php - 提交数据并重定向到同一页面后的 Laravel 自定义错误消息,并带有一些小错误信息
- xml - XML Schema - 两个两个元素的键约束
- node.js - 为数据中的某些值创建特定元素
- python - Python 3.7:将代理应用于 pip 安装的所有部分,无法维护代理变量