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

Program stops working, pointer error i'm sure

本文关键字:错误 指针 停止工作 程序      更新时间:2023-10-16

我有这个程序,但我仍然习惯于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

Prog1类.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 = '';
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

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

Prog1Struct *emptyStruct = '';//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];