gpt4 book ai didi

c++ - 在 C++ 中通过引用传递二维动态字符串数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:24 25 4
gpt4 key购买 nike

我必须为这个项目使用一个动态数组,但我不能通过引用传递它,我不知道该怎么做,我初始化了二维动态数组,但不知道如何通过引用传递它。

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>

using namespace std;

#define row 5
#define col 14
typedef string* StrArrPtr;

void set_up_array(string (&&layout_array)[row][col]);

int main()
{

StrArrPtr *layout_array = new StrArrPtr[col];
for(int i = 0; i < row; i++)
{
layout_array[i] = new string[col];
}

//string layout_array[row][col];

set_up_array(layout_array);

for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
if(j == 1 && i > 0)
{
cout << right << setw(11);
}
cout << "| " << layout_array[i][j] << " ";
}
cout << "|" << endl;
}

return 0;

}

void set_up_array(string (&&layout_array)[row][col])
{
layout_array[0][0] = "Lab Number"; //First Column / first row
layout_array[1][0] = "1"; // second row
layout_array[2][0] = "2"; // third row
layout_array[3][0] = "3"; // fourth row
layout_array[4][0] = "4"; // fifth row


}

我是 C++ 的新手,所以解决方案可能非常明显,但我就是看不到它。任何帮助将不胜感激。

最佳答案

考虑到您在 set_up_array 中对数组所做的操作,您不需要通过引用传递实际的 string*,因为您只是取消引用它 (告诉您的计算机在哪里寻找 string) 并更改位于该索引处的 string 的值。当您在 C/C++ 中传递一个数组时,您只是传递一个 int,所以不要担心引用,除非您正在修改指针指向的内容。

(就像string * &ref)

关于c++ - 在 C++ 中通过引用传递二维动态字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48375341/

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