C++ 为什么这段代码中有分段错误? #包括 #包括 使用名称空间std; //创建一个结构,使其具有型号和名称以及指向下一本书的指针 结构组件 { 串南; 国际货币基金组织; comp*next; }; //定义指向compPtr的comp指针 typedef comp*compPtr; int main() { compPtr head=NULL; compPtr last=NULL; if(head==NULL) { 压缩机温度; temp->nam=“戴尔”; 温度->mnum=45215; temp->next=NULL; 压头=温度; 最后=温度; } if(head!=NULL) { compPtr temp1; temp1->nam=“Mac”; temp1->mnum=1255; temp1->next=NULL; last->next=temp1; last=temp1; } compPtr-compnext; COMNEXT=头部; if(compnext==NULL) { 库特
为什么这段代码中有分段错误 不要将指针“隐藏”在C++ 为什么这段代码中有分段错误? #包括 #包括 使用名称空间std; //创建一个结构,使其具有型号和名称以及指向下一本书的指针 结构组件 { 串南; 国际货币基金组织; comp*next; }; //定义指向compPtr的comp指针 typedef comp*compPtr; int main() { compPtr head=NULL; compPtr last=NULL; if(head==NULL) { 压缩机温度; temp->nam=“戴尔”; 温度->mnum=45215; temp->next=NULL; 压头=温度; 最后=温度; } if(head!=NULL) { compPtr temp1; temp1->nam=“Mac”; temp1->mnum=1255; temp1->next=NULL; last->next=temp1; last=temp1; } compPtr-compnext; COMNEXT=头部; if(compnext==NULL) { 库特,c++,segmentation-fault,C++,Segmentation Fault,为什么这段代码中有分段错误 不要将指针“隐藏”在typedef后面——这只会让您感到困惑 您的代码相当于: #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; c
typedef
后面——这只会让您感到困惑
您的代码相当于:
#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;
}
}
}
欢迎来到Stack Overflow!请回答您的问题,向我们展示您所做的调试类型。我希望您已经在Valgrind或类似的检查器中运行过,并使用诸如GDB之类的调试器进行过调查。请确保您也启用了全套编译器警告。这些工具告诉了您什么,以及提供了哪些信息他们失踪了?读埃里克·利珀特的。
comp *temp; // Note: does not point *anywhere*.
temp->nam = "Dell"; // Dereferencing uninitialized pointer, undefined behavior,
// often crash.