指针段错误问题...
同时,我已经用了几个星期的 c++,但我又遇到了那个问题。
基本上我已经给出了这些类(class)。我不能改变他们。我从 _ns3__importAuftragResponse kout;
class SOAP_CMAC _ns3__importAuftragResponse
{
public:
ns2__SOAPImportResult *return_;
...
class SOAP_CMAC ns2__SOAPImportResult
{
public:
bool *error;
int *numberOfIgnoreds;
....
我的代码需要检查 numberOfIgnoreds
第一种方法
ns2__SOAPImportResult* imp_result;
imp_result = kout.return_;
int num;
num = *imp_result->numberOfIgnoreds;
或者我用
ns2__SOAPImportResult imp_result;
imp_result = *(kout.return_);
int* num;
*num = *imp_result.numberOfIgnoreds;
我主要遇到段错误 我通常知道运行时会发生什么,但无法想出正确的颂歌。请帮忙。
编辑
感谢您的回答,Nawaz,但仍需要一些理解
ns2__SOAPImportResult * imp_ptr = new ns2__SOAPImportResult;
imp_ptr = kout.return_;
int * num = new (int);
// next line segfaults
*num = *imp_ptr->numberOfIgnoreds;
让我难以理解的是,如何或为什么为已经“存在”的东西分配内存,因为存在对象 kout 的成员 return_
那么说我需要为分配给它的变量(当然是同一类型)分配内存是否正确?
最佳答案
您很可能没有为您在引用的代码中使用的以下成员分配内存。
ns2__SOAPImportResult *return_; //in the class _ns3__importAuftragResponse
int *numberOfIgnoreds; //in the class ns2__SOAPImportResult
除此之外,我看不到任何可能出错的地方!
确保为这些成员(以及程序中的所有其他指针)分配内存在使用它们之前。您可以使用 new
来分配内存。或者,您也可以使用 malloc()
。无论您使用什么,都要始终如一地使用它,并在完成后释放内存,分别使用 delete
或 free()
!
关于c++ - 指针段错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5349599/