简体   繁体   English

访问2D结构时程序崩溃

[英]Program crashing when accessing 2D struct

So I have spent countless hours trying to find the answer to this question. 所以我花了无数个小时试图找到这个问题的答案。 I have found something close to it but not exactly so I guess I will post here. 我发现了一些接近它的东西但不完全如此我想我会在这里发布。

I'm trying to create a 2D array of structs. 我正在尝试创建一个二维结构数组。 I will call a function to create the struct and input values into the struct. 我将调用一个函数来创建结构并将值输入到结构中。 This is an example of a possible output: 这是一个可能的输出示例:

input: int 5, int 5 输入:int 5,int 5

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

I was able to create the struct but my program keeps crashing when I try to input the values. 我能够创建结构但我的程序在我尝试输入值时不断崩溃。 Any inputs would be great! 任何输入都会很棒! Here's my code below. 这是我下面的代码。

struct values{
int mult;
float div;
};

values** create_table(int row, int col){
values** tab = new values*[row];
values* one_row = new values[col];
for (int i = 0; i < row; i++){
    tab[i] = one_row;
}
return tab;
}

void set_m_values(values** tab, int row, int col){
for (int i = 0; i < row; i++){
    for (int j = 0; i < col; j++){
        tab[i][j].mult = (i+1)*(j+1);
    }
}
}

int main() {
int row = 5;
int col = 5;
values** tab = create_table(row, col);
set_m_values(tab, row, col);
for (int i = 0; i < row; i++){
    for (int j = 0; j< col; j++){
        cout <<tab[0][i].mult;
    }
    cout <<endl;
}
return 0;
}

Your initialization is wrong 你的初始化是错误的

values* one_row = new values[col];
for (int i = 0; i < row; i++){
    tab[i] = one_row;

This is creating one row, and assigning it to every row. 这是创建一行,并将其分配给每一行。

You probably meant to do: 你可能打算这样做:

values** tab = new values*[row];

for (int i = 0; i < row; i++)
{
    tab[i] = new values[col];
}

That being said you really should be using either std::array or std::vector . 那就是说你真的应该使用std::arraystd::vector

ALSO, and this is what's causing the crash, in set_m_values , you have an incorrect comparison: 另外,这就是造成崩溃的原因,在set_m_values ,你的比较不正确:

for (int j = 0; i < col; j++){ // notice the i in there

should be: 应该:

for (int j = 0; j < col; j++){ // replaced i with j

Most likely you copy pasted and forgot to change it. 你最有可能复制粘贴并忘记更改它。 I would like to stress the fact that you really should be using standard library containers like vector for this. 我想强调的是,你真的应该使用像vector这样的标准库容器。 For example you could have: 例如,您可以:

// with this you don't need the create_table function
std::vector< std::vector<values> > table(row, std::vector<values>(col));

PS: You have a memory leak in your code because deletes are not called. PS:您的代码中存在内存泄漏,因为未调用删除。 Which is not a problem you would have with std::vector 这对std::vector来说不是问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM