D:\Program Files(x86)\C++(从入门到放弃)\01 结构体定义和使用\x64\Debug\01 结构体定义和使用.exe (进程 23260)已退出,代码为 -1073741819。

昨天晚上学习C++的时候,学习到结构体,跟着老师写代码发现何老师一模一样的代码总是编不过去。没有打印信息,总是报错。

源代码如下:

#include
#include
#include
using namespace std;

struct student
{
    string name;
    int score;
};

struct teacher
{
    string name;
    struct student sArray[5];
};

void allocateSpace(struct teacher tarray[], int len)
{
    string nameSeed = “ABCDE”;
    for (int i = 0; i < len; i++)
    {
        tarray[i].name = “teacher_”;
        tarray[i].name += nameSeed[i];
        for (int j = 0; j < 5; j++)
        {
            tarray[i].sArray[j].name = “Student_”;
            tarray[i].sArray[j].name += nameSeed[j];

            tarray[i].sArray[j].score = 60;
        }
    }
}

void printinfo(struct teacher tarray[], int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << "老师姓名:" << tarray[i].name << endl;
        for (int j = 0; j < 5; j++)
        {
            cout << "\t学生姓名: " << tarray[i].sArray[j].name <<
                ” 考试分数: ” << tarray[i].sArray[j].score
                <<endl;
        }
    }
}

int main()
{
    struct teacher tarray[3];
    int len = sizeof(tarray) / sizeof(tarray[0]);
    srand((unsigned int)time(NULL));
    allocateSpace(tarray, len);
    printinfo(tarray, len);
    return 0;
}

仔细研究发现在同一个项目中的另一个源文件中有一个同名结构体,但是数据属性不一样。

目标文件为07,代码上面已经附了。此处和07源文件中的teacher熟据属性不一致。导致执行报错。

 

这个未知的错误,完全查看不出来。也无从调试。

找出问题的过程:

我把整个源码放到code::blocks中进行编译成功运行。后来把该项目中的源文件按个“右键-属性-从生成中排除- 是”排除之后单个编译通过,挨个添加到04时编译不过,添加左右的除了04文件其他均通过。由此判断是为04问题。但是04中的main函数我改为main04,也无法编译。仔细查看04代码发现有一个结构体

struct teacher
{
    int id;
    string name;
    int age;
    struct student stu;
};

和07中结构体

struct teacher
{
    string name;
    struct student sArray[5];
};

名字一模一样,单数数据属性不一样。修改04中的teacher为Teacher之后编译通过。

 

结论:

visual studio 2022在同一个项目中可以有同名结构体,但是数据属性必须要一致,否则会报错误(该错误很难找且很诡异)。