c - C中的链表。分段错误
问题描述
#include <stdio.h>
struct mychar{
char value;
struct mychar *nextPtr;
};
typedef struct mychar Mychar;
typedef Mychar *MycharPtr;
void insert(MycharPtr *, char );
void printlist(MycharPtr);
int main(){
MycharPtr startPtr = NULL;
char b = 'b';
insert(&startPtr, b);
printlist(startPtr);
}
void insert(MycharPtr *sPtr, char newvalue){
MycharPtr newlinkPtr;
if (*sPtr == NULL){
newlinkPtr->value = newvalue;
newlinkPtr->nextPtr = NULL;
}
*sPtr = newlinkPtr;
}
void printlist(MycharPtr currentPtr){
printf("%c", currentPtr->value);
}
我刚开始只添加一个字符。如果我连那个都做不到,我就不能继续做其他事情。
它给了我分段错误,但我真的不知道为什么。
另外,我仍然不明白为什么在insert
通话中我应该写&
但在printlist
通话中我不应该写&
。
解决方案
您实际上还没有为newlinkPtr
. 因此,您只是取消引用并尝试写入未初始化的指针,从而导致未定义的行为。
中insert
,可以修改为:
MycharPtr newlinkPtr = malloc(sizeof *newlinkPtr);
if (!newlinkPtr) {
perror("malloc");
return;
}
...
这在某种程度上也说明了为什么对结构指针进行类型定义可能会误导并被认为是一种不好的做法。我建议避免它。
推荐阅读
- php - long2ip 不适用于数据库中的字符串
- sql - 在 SQL 中使用 OR 排除结果的查询
- java - 从 Java 应用程序将数据块保存到数据库中
- sql - 如何使用结果集作为输入从日历表中获取所有行
- jackson - Jackson TreeModel vs 数据绑定
- jquery - 为什么 $.get 在执行此代码时会延迟?
- javascript - 在窗口调整大小时更改元素的大小
- php - Wordpress 在帖子内容中错误地显示 HTML 实体和十六进制实体
- typescript - 打字稿可以缩小泛型类型中的联合类型吗?
- django - 变量未显示在 Django 模板上