gpt4 book ai didi

c++ - 动态创建一个 3x2 矩阵;打印它显示一个 2x2 矩阵

转载 作者:行者123 更新时间:2023-11-28 05:46:41 27 4
gpt4 key购买 nike

我遇到了问题。我想创建二维数组 rows=3 cols=2我的代码如下

int **ptr;
int row=3;
int col=2;
ptr=new int *[col];
for (int i=0;i<col;i++)
{
ptr[i]=new int [row];
}
for (int i=0;i<row;i++)
{
for (int j=0;j<col;j++)
{
cout<<ptr[i][j]<<" ";
}
cout<<endl;
}

但我得到输出 (2*2)

0 0
0 0

最佳答案

当您使用二维数组时,您会遇到以下情况:

HOLDS YOUR ROWS
|
|
[x0] ([x0_1][x0_2][x0_3]...[x0_n]) <- ROW ARRAY
[x1] ([x1_1][x1_2][x1_3]...[x1_n]) <- ROW ARRAY
[x2] ([x2_1][x2_2][x2_3]...[x2_n]) <- ROW ARRAY
. .
. .
. .
[xm] ([xm_1][xm_2][xm_3]...[xm_n]) <- ROW ARRAY

这意味着首先您必须创建每一行:

for (int i=0;i<row;i++)
{
ptr[i]=new int[col]; // Each row has col number of cells
}

从我帖子开头的表格中,这会为您提供每个([xP_1][xP_2][xP_3]...[xP_n])

代码的下一部分必须实际初始化每一行中的单元格,因此在外循环中必须遍历行,然后在内循环中必须遍历列,因为每一行都有来自 ptr[i]=new int[COL];.所以我们得到:

for (int i=0;i<row;i++)
{
for (int j=0;j<col;j++)
{
cout<<ptr[i][j]<<" ";
}
cout<<endl;
}

所以最后我们有(我已经将 row 替换为 rows 并将 col 替换为 cols为了让你更易读......我希望 :D):

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
int **ptr;
int rows = 3;
int cols = 2;
ptr = new int *[rows];
for (int row=0; row<rows; row++)
{
ptr[row]=new int [cols];
}
for(int row=0; row<rows; row++)
{
for(int col=0; col<cols; col++)
{
ptr[row][col] = 0;
cout << ptr[row][col] << " ";
}
cout << endl;
}

// Do something with the 2D array
// ...

// Delete all
for(int row = 0; row < rows; row++) delete[] ptr[row];
delete[] ptr;

return 0;
}

输出是:

0 0
0 0
0 0

希望这对您有所帮助。还要记住,您需要使用一些值来初始化数组的单元格。像您一样保留它并不是一个好的做法 - 创建然后直接转到显示部分而不添加任何值。

关于c++ - 动态创建一个 3x2 矩阵;打印它显示一个 2x2 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36084264/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com