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


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

相关内容

  • 没有找到相关文章

最新更新