程序停止工作,指针错误我敢肯定

时间:2014-01-03 23:29:48

标签: c++ arrays class structure pointers

我有这个程序,我仍然习惯于C ++指针,所以这可能是一个问题。但是当调用getStructData()函数时,程序崩溃了。我可能搞砸了与我使用的结构的指针有关,但我现在还不确定。任何提示或帮助表示赞赏。谢谢,在人们开始疯狂的贬低之前,这不是我学校的家庭作业,我只是在圣诞假期期间去其他学校做作业练习。

Prog1Struct.h

#ifndef INCLUDED_PROG1STRUCT
#define INCLUDED_PROG1STRUCT

struct Prog1Struct
{

int m_iVal;
double m_dArray[5];
char m_sLine[80];

};

#endif

Prog1Class.h

#ifndef PROG1CLASS
#define PROG1CLASS
#include "Prog1Struct.h"



class Prog1Class
{

private:
Prog1Struct myStruct[5];



public:

/*Prog1Class();
~Prog1Class();*/
void setStructData();
void getStructData(int structureArrayIndex, struct Prog1Struct *info);
void printStruct(int indexPriv);
void printData(); 

};

#endif

Prog1Class.cpp

#ifndef INCLUDED_PROG1CLASS
#define INCLUDED_PROG1CLASS

#include <iostream>
#include <string>
#include "Prog1Class.h"
#include "Prog1Struct.h"
#include <time.h>

using namespace std;




void Prog1Class::setStructData()
{
for (int i = 0; i<5; i++)
{
cout << "Enter an integer: ";
cin >> myStruct[i].m_iVal;
for (int j = 0; j < 5; j++)
{
    cout << endl << "Enter a double: ";
    cin >> myStruct[i].m_dArray[j];
}
cout << endl << "Enter a string: ";
cin.ignore(256, '\n');
cin.getline(myStruct[i].m_sLine, 80, '\n');
cout << endl;
}
}

//takes in index for array, and pointer to a struct of the type in Prog1Struct.h.  Copies     all data from the private struct at the given index into the struct of the pointer     argument.
void Prog1Class::getStructData(int structureArrayIndex, struct Prog1Struct *info)
{

*info = myStruct[structureArrayIndex];
cout << "Printing *info from getStructData function" << endl;
cout << info;
}


void Prog1Class::printStruct(int indexPriv)
{
cout << myStruct[indexPriv].m_iVal << " ";
for (int k = 0; k < 5; k++)
{
cout << myStruct[indexPriv].m_dArray[k] << " ";
}
cout << myStruct[indexPriv].m_sLine << " ";
}


int main(void)
{
Prog1Class c;
Prog1Struct *emptyStruct = '\0';
cout << "setStructData called:" << endl;
c.setStructData();
cout << "getStructData called:" << endl;
//error comes here, at getStructData.  
c.getStructData(2, emptyStruct);
cout << "printStruct called:" << endl;
c.printStruct(2);


cin.get();
}



#endif

1 个答案:

答案 0 :(得分:0)

您正在尝试为空指针赋值。

Prog1Struct *emptyStruct = '\0';//set emptyStruct to 0 (This means it points at address 0, not holding a 0 value)
cout << "setStructData called:" << endl;
c.setStructData();
cout << "getStructData called:" << endl;
//error comes here, at getStructData.  
c.getStructData(2, emptyStruct);//emptyStruct is still = 0

所以在函数中,info = 0。

void Prog1Class::getStructData(int structureArrayIndex, struct Prog1Struct *info)
{

*info = myStruct[structureArrayIndex];//This line is trying to write to a section of memory you don't have access to (address 0)

你想要这个。 (未经测试)这将使信息指向myStruct [structureArrayIndex](不将myStruct [structureArrayIndex]的内容复制到info)。指针只指向事物(如结构或其他类型),它们不能包含结构。

info = &myStruct[structureArrayIndex];