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

标签 c++ segmentation-fault

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

相关文章:

c - 递归函数,传递参数 - 段错误

c - 执行thread_kill时出现segmentation fault

c++ - 如何在 cpp 宏中生成换行符?

c - 如何修复打印链表时的段错误?

c++ - 为什么这个 OpenCV 代码会出现段错误?

c - 使用指向数组的结构体进行队列

c++ - 控制台输出笑脸

c++ - 二维数组中的指针

c++ - 添加每个可能的 xor-sum 子数组的和的算法

c++ - binary_search、find_if 和 <functional>