繁体   English   中英

为什么此代码中存在分段错误?

[英]Why is there a Segmentation Fault in this code?

#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;
        }
    }
}

为什么此代码中存在分段错误?

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

您的代码相当于:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM