gpt4 book ai didi

c++ - 为什么此代码中存在段错误?

转载 作者:行者123 更新时间:2023-12-02 22:25:25 25 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;

//create a struct to have model number and name and a pointer to next book
struct comp
{
string nam;
int mnum;
comp* next;
};

// define comp pointer to compPtr
typedef comp* compPtr;

int main()
{
compPtr head = NULL;
compPtr last = NULL;

if (head == NULL)
{
compPtr temp;
temp->nam = "Dell";
temp->mnum = 45215;
temp->next = NULL;
head = temp;
last = temp;
}
if (head != NULL)
{
compPtr temp1;
temp1->nam = "Mac";
temp1->mnum = 1255;
temp1->next = NULL;
last->next = temp1;
last = temp1;
}

compPtr compnext;
compnext = head;
if (compnext == NULL)
{
cout<<"NO COMPUTERS";
}
else
{
while(compnext != NULL)
{
cout<<compnext->nam<<endl;
cout<<compnext->mnum<<endl;
compnext = compnext->next;
}
}
}

最佳答案

Why is there a Segmentation Fault in this code?

不要将指针“隐藏”在typedef后面——它只会让你感到困惑。

您的代码相当于:

comp *temp;          // Note: does not point *anywhere*.
temp->nam = "Dell"; // Dereferencing uninitialized pointer, undefined behavior,
// often crash.

关于c++ - 为什么此代码中存在段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259002/

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