将int [5] [5]类型的变量传递给需要int **的函数

时间:2022-09-06 10:19:14

I'd like to test a function that takes runtime-allocated multidimensional arrays, by passing it a hardcoded array.

我想通过传递硬编码数组来测试一个采用运行时分配的多维数组的函数。

The function has a signature of void generate_all_paths(int** maze, int size) and the array is defined as int arr[5][5] = {REMOVED}.

该函数具有void generate_all_paths(int ** maze,int size)的签名,并且该数组被定义为int arr [5] [5] = {REMOVED}。

I'm not exactly sure how to properly coerce the array for the function (or if that is impossible).

我不确定如何正确强制该函数的数组(或者如果这是不可能的)。

7 个解决方案

#1


This multi dimensional array topic unfortunately confuses so many C++ programmers. Well, here is the solution:

不幸的是,这个多维数组主题让许多C ++程序员感到困惑。嗯,这是解决方案:

void generate_all_paths(int (*maze)[5], int size);

That is what the function declaration has to look like. An alternative, but fully equivalent is

这就是函数声明必须看起来的样子。另一种选择,但完全相同

void generate_all_paths(int maze[][5], int size);

Both are creating a parameter that is a pointer to an array of 5 integers. You can then pass your array of arrays of 5 integers to that function:

两者都创建一个参数,该参数是指向5个整数数组的指针。然后,您可以将包含5个整数的数组数组传递给该函数:

generate_all_paths(arr, 5);

Because your array's first element is an array of 5 integers, it will be converted automatically (implicitly) to a pointer to that first element when passed to that function.

因为数组的第一个元素是一个包含5个整数的数组,所以当传递给该函数时,它将自动(隐式)转换为指向第一个元素的指针。

In the comments, you have shown you are bound to an int**, because both your inner and outer dimension must have runtime values. A multi-dimensional array can not be used anymore. What you can do for testing purposes then is to create an array of pointers like this:

在注释中,您已经显示您已绑定到int **,因为内部和外部维度都必须具有运行时值。不能再使用多维数组。您可以为测试目的做的是创建一个指针数组,如下所示:

int store[5 * 5] = { ..... };
int *arr[5] = { store, store + 5, store + 10, store + 15, store + 20 };

Then, actually, you can have your function accept a int**. As the first element of you array then is a int*, it will be converted to a int** automatically. Another way of doing this is keeping the data in the 2 dimensional array, but just creating a "view" structured of pointers to that array:

那么,实际上,你可以让你的函数接受一个int **。因为你的数组的第一个元素是int *,它将自动转换为int **。另一种方法是将数据保存在二维数组中,但只需创建一个由该数组指针构成的“视图”:

int *arr[5] = { store[0], store[1], store[2], store[3], store[4] };

Where store is your int[5][5] array. Since store[n] accesses the n'th sub-array of that two-dimensional array and the element type of it is int, the pointer-converted type of it is int*, which will be compatible again.

store是你的int [5] [5]数组。由于store [n]访问该二维数组的第n个子数组,并且它的元素类型是int,因此它的指针转换类型是int *,它将再次兼容。

#2


You can write:

你可以写:

void display(char **a)

And then use a[i][j] to refer to elements in it.

然后使用[i] [j]来引用其中的元素。

The declaration char ** means "pointer to pointer to integer". To break it down into steps:

声明char **表示“指向整数的指针”。把它分解为几个步骤:

char *b = a[i];

That gets you a pointer to the first element of the i'th array in the array-of-arrays.

这会让你指向数组数组中第i个数组的第一个元素。

char c = b[j];

That gets you the j'th element in the array b.

这将获得数组b中的第j个元素。

The next problem you'll have is of allocating such an array-of-arrays.

您将遇到的下一个问题是分配这样的数组数组。

char **arrayOfArrays = new char *[10];

for (int n = 0; n < 10; n++)
    arrayOfArrays[n] = new char[20];

That allocates an array of 10 arrays, each "child" array having 20 characters.

这将分配一个包含10个数组的数组,每个“子”数组包含20个字符。

In C/C++, array access syntax is just a way of retrieving a value some distance away from a pointer.

在C / C ++中,数组访问语法只是一种从指针中检索一定距离的值的方法。

char *p = "Hello";

char *pl = p + 2;   // get pointer to middle 'l'
char l = *pl;       // fetch

char o = p[4];      // use array syntax instead

#3


void display(char ** array) should work. Also I don't think that it is a reserved word in standard C/C++.

void display(char ** array)应该可以工作。另外我不认为它是标准C / C ++中的保留字。

#4


And also, why is array a reserved word?

而且,为什么数组是一个保留字?

It isn't. You are probably using Visual Studio where it's displayed as a keyword due to its use in C++/CLI as a native managed type. However, this is irrelevant for C++ and Visual Studio is misleading in that regard.

事实并非如此。您可能正在使用Visual Studio作为关键字显示,因为它在C ++ / CLI中用作本机托管类型。但是,这与C ++无关,而Visual Studio在这方面具有误导性。

As to your problem: You can simply pass a pointer-to-pointers-to-char and then pass your nested array directly (provided you are working with a dynamically allocated array):

至于你的问题:你可以简单地传递一个指向指针到char的指针然后直接传递你的嵌套数组(假设你正在使用一个动态分配的数组):

void display(char** array) …

That said, your function assumes a fixed, known array length and some other details. Better would be to use a nested std::vector, or std::string (for instance). Using such existing data types makes your life much easier.

也就是说,您的函数假设一个固定的,已知的数组长度和一些其他细节。更好的方法是使用嵌套的std :: vector或std :: string(例如)。使用这些现有数据类型可以让您的生活更轻松。

void display(std::vector<std::string> const& array) {
    for (size_t i = 0; i < array.length(); ++i)
        cout << array[i] << endl;
}

To take advantage of this, your calling code needs to be changed as well to use these data structures instead of plain C arrays on chars.

要利用这一点,您的调用代码也需要更改,以便在chars上使用这些数据结构而不是纯C数组。

#5


The Earwicker's answer is missing an important fact. What he is proposing is an array of arrays. For the first this wastes memory for the array of pointers ("char **arrayOfArrays = new char *[10]" is the creation point of this). For the second the array of chars may then not be a continuous block of memory, which is often a problem. The only workaround in C++ is to create a one dimensional array and calculate the indexes when you need them.

Earwicker的答案错过了一个重要的事实。他提出的是一系列数组。对于第一个,这浪费了指针数组的内存(“char ** arrayOfArrays = new char * [10]”是这个的创建点)。对于第二个,字符阵列可能不是连续的存储器块,这通常是一个问题。 C ++中唯一的解决方法是创建一维数组并在需要时计算索引。

char *b = new char[width*height];

then you can refer to element x,y (x is along width, y along height) like this

那么你可以像这样引用元素x,y(x是沿宽度,y是沿着高度)

char c=b[width*y+x];

This may be however a bit slower than the solution above (measured on GCC 3.4.5), so if you are not interested in continuous memory (for example you always access the elements with [][], never by adding integer to a pointer and dereferencing it), then you should use the array af arrays. However, if you are interested in having the continuous memory, e.g. to pass it as initializer to an std::string object or to send it as a whole through a network, you should use the second one.

然而,这可能比上面的解决方案慢一点(在GCC 3.4.5上测量),所以如果你对连续内存不感兴趣(例如你总是用[] []访问元素,那么永远不要通过向指针添加整数并取消引用它),那么你应该使用数组af数组。但是,如果您对连续记忆感兴趣,例如要将它作为初始化程序传递给std :: string对象或通过网络将其作为一个整体发送,您应该使用第二个。

#6


The best is to use pointers, but Borland C++ admits passing arrays as parameters for functions. Look at this code (includes: iostream and conio):

最好的方法是使用指针,但Borland C ++允许传递数组作为函数的参数。看看这段代码(包括:iostream和conio):

////////////////////////////////////////////

void ReceivedArray(char x[5]){

for (int i=0; i<5; i++ )
cout << x[i];

}

void main(){

char *x = new char[5];

for (int i=0; i<5; i++ )
x[i]='o';

ReceivedArray(x);
getchar();
}


///////////////////////////////////////////////////////////////


For passing 2D arrays (oops! some lines in spanish, sorry!):

(includes: iostream, stdlb, stdio and math)


/////////////////////////////////////////////////

using namespace std;

void ver(int x[][20]){
for(int i=0; i<15; i++)  {
  for(int j=0; j<20; j++) {
   cout<< x[i][j] <<" ";       }
   cout << "\n";        }

}

void cambiar0(int x[][20]){ int n[255];
   for (int i=255; i>=0; i--)
    n[255-i]=i;


for(int i=0; i<15; i++)
  for(int j=0; j<20; j++)
      for(int k=0; k<255; k++)
       if(x[i][j]==n[k])  {
          x[i][j]=k; break;  }  
}

int main(int argc, char* argv[]){
int x[15][20]; char a; 

for(int i=0; i<15; i++)
  for(int j=0; j<20; j++)
   x[i][j]=rand()%255;

  cout << "¿desea ver la matriz? s/n ";
 cin >> a;
 if(a=='s') ver(x);

 cambiar0(x);

 cout << "\n\n";
 cout << "¿desea ver la matriz? s/n ";
 cin >> a;
 if(a=='s') ver(x);

system("PAUSE"); return 0;
}

///////////////////////////////////

Hope this is what you meant.

希望这就是你的意思。

#7


arr is a pointer to the multi-dimesional array you have and is actually a pointer to an int. Now since your function accepts a pointer to an int pointer, you need to get the address of arr using: &arr and pass that to the function so that you will have this code:

arr是指向你所拥有的多维数组的指针,实际上是指向int的指针。现在,由于你的函数接受一个指向int指针的指针,你需要使用:&arr获取arr的地址并将其传递给函数,以便你拥有这个代码:

To coerce the array: Pass &arr to the function. To reference the array inside the func: *maze[x][y]

强制数组:传递和arr到函数。引用func中的数组:* maze [x] [y]

#1


This multi dimensional array topic unfortunately confuses so many C++ programmers. Well, here is the solution:

不幸的是,这个多维数组主题让许多C ++程序员感到困惑。嗯,这是解决方案:

void generate_all_paths(int (*maze)[5], int size);

That is what the function declaration has to look like. An alternative, but fully equivalent is

这就是函数声明必须看起来的样子。另一种选择,但完全相同

void generate_all_paths(int maze[][5], int size);

Both are creating a parameter that is a pointer to an array of 5 integers. You can then pass your array of arrays of 5 integers to that function:

两者都创建一个参数,该参数是指向5个整数数组的指针。然后,您可以将包含5个整数的数组数组传递给该函数:

generate_all_paths(arr, 5);

Because your array's first element is an array of 5 integers, it will be converted automatically (implicitly) to a pointer to that first element when passed to that function.

因为数组的第一个元素是一个包含5个整数的数组,所以当传递给该函数时,它将自动(隐式)转换为指向第一个元素的指针。

In the comments, you have shown you are bound to an int**, because both your inner and outer dimension must have runtime values. A multi-dimensional array can not be used anymore. What you can do for testing purposes then is to create an array of pointers like this:

在注释中,您已经显示您已绑定到int **,因为内部和外部维度都必须具有运行时值。不能再使用多维数组。您可以为测试目的做的是创建一个指针数组,如下所示:

int store[5 * 5] = { ..... };
int *arr[5] = { store, store + 5, store + 10, store + 15, store + 20 };

Then, actually, you can have your function accept a int**. As the first element of you array then is a int*, it will be converted to a int** automatically. Another way of doing this is keeping the data in the 2 dimensional array, but just creating a "view" structured of pointers to that array:

那么,实际上,你可以让你的函数接受一个int **。因为你的数组的第一个元素是int *,它将自动转换为int **。另一种方法是将数据保存在二维数组中,但只需创建一个由该数组指针构成的“视图”:

int *arr[5] = { store[0], store[1], store[2], store[3], store[4] };

Where store is your int[5][5] array. Since store[n] accesses the n'th sub-array of that two-dimensional array and the element type of it is int, the pointer-converted type of it is int*, which will be compatible again.

store是你的int [5] [5]数组。由于store [n]访问该二维数组的第n个子数组,并且它的元素类型是int,因此它的指针转换类型是int *,它将再次兼容。

#2


You can write:

你可以写:

void display(char **a)

And then use a[i][j] to refer to elements in it.

然后使用[i] [j]来引用其中的元素。

The declaration char ** means "pointer to pointer to integer". To break it down into steps:

声明char **表示“指向整数的指针”。把它分解为几个步骤:

char *b = a[i];

That gets you a pointer to the first element of the i'th array in the array-of-arrays.

这会让你指向数组数组中第i个数组的第一个元素。

char c = b[j];

That gets you the j'th element in the array b.

这将获得数组b中的第j个元素。

The next problem you'll have is of allocating such an array-of-arrays.

您将遇到的下一个问题是分配这样的数组数组。

char **arrayOfArrays = new char *[10];

for (int n = 0; n < 10; n++)
    arrayOfArrays[n] = new char[20];

That allocates an array of 10 arrays, each "child" array having 20 characters.

这将分配一个包含10个数组的数组,每个“子”数组包含20个字符。

In C/C++, array access syntax is just a way of retrieving a value some distance away from a pointer.

在C / C ++中,数组访问语法只是一种从指针中检索一定距离的值的方法。

char *p = "Hello";

char *pl = p + 2;   // get pointer to middle 'l'
char l = *pl;       // fetch

char o = p[4];      // use array syntax instead

#3


void display(char ** array) should work. Also I don't think that it is a reserved word in standard C/C++.

void display(char ** array)应该可以工作。另外我不认为它是标准C / C ++中的保留字。

#4


And also, why is array a reserved word?

而且,为什么数组是一个保留字?

It isn't. You are probably using Visual Studio where it's displayed as a keyword due to its use in C++/CLI as a native managed type. However, this is irrelevant for C++ and Visual Studio is misleading in that regard.

事实并非如此。您可能正在使用Visual Studio作为关键字显示,因为它在C ++ / CLI中用作本机托管类型。但是,这与C ++无关,而Visual Studio在这方面具有误导性。

As to your problem: You can simply pass a pointer-to-pointers-to-char and then pass your nested array directly (provided you are working with a dynamically allocated array):

至于你的问题:你可以简单地传递一个指向指针到char的指针然后直接传递你的嵌套数组(假设你正在使用一个动态分配的数组):

void display(char** array) …

That said, your function assumes a fixed, known array length and some other details. Better would be to use a nested std::vector, or std::string (for instance). Using such existing data types makes your life much easier.

也就是说,您的函数假设一个固定的,已知的数组长度和一些其他细节。更好的方法是使用嵌套的std :: vector或std :: string(例如)。使用这些现有数据类型可以让您的生活更轻松。

void display(std::vector<std::string> const& array) {
    for (size_t i = 0; i < array.length(); ++i)
        cout << array[i] << endl;
}

To take advantage of this, your calling code needs to be changed as well to use these data structures instead of plain C arrays on chars.

要利用这一点,您的调用代码也需要更改,以便在chars上使用这些数据结构而不是纯C数组。

#5


The Earwicker's answer is missing an important fact. What he is proposing is an array of arrays. For the first this wastes memory for the array of pointers ("char **arrayOfArrays = new char *[10]" is the creation point of this). For the second the array of chars may then not be a continuous block of memory, which is often a problem. The only workaround in C++ is to create a one dimensional array and calculate the indexes when you need them.

Earwicker的答案错过了一个重要的事实。他提出的是一系列数组。对于第一个,这浪费了指针数组的内存(“char ** arrayOfArrays = new char * [10]”是这个的创建点)。对于第二个,字符阵列可能不是连续的存储器块,这通常是一个问题。 C ++中唯一的解决方法是创建一维数组并在需要时计算索引。

char *b = new char[width*height];

then you can refer to element x,y (x is along width, y along height) like this

那么你可以像这样引用元素x,y(x是沿宽度,y是沿着高度)

char c=b[width*y+x];

This may be however a bit slower than the solution above (measured on GCC 3.4.5), so if you are not interested in continuous memory (for example you always access the elements with [][], never by adding integer to a pointer and dereferencing it), then you should use the array af arrays. However, if you are interested in having the continuous memory, e.g. to pass it as initializer to an std::string object or to send it as a whole through a network, you should use the second one.

然而,这可能比上面的解决方案慢一点(在GCC 3.4.5上测量),所以如果你对连续内存不感兴趣(例如你总是用[] []访问元素,那么永远不要通过向指针添加整数并取消引用它),那么你应该使用数组af数组。但是,如果您对连续记忆感兴趣,例如要将它作为初始化程序传递给std :: string对象或通过网络将其作为一个整体发送,您应该使用第二个。

#6


The best is to use pointers, but Borland C++ admits passing arrays as parameters for functions. Look at this code (includes: iostream and conio):

最好的方法是使用指针,但Borland C ++允许传递数组作为函数的参数。看看这段代码(包括:iostream和conio):

////////////////////////////////////////////

void ReceivedArray(char x[5]){

for (int i=0; i<5; i++ )
cout << x[i];

}

void main(){

char *x = new char[5];

for (int i=0; i<5; i++ )
x[i]='o';

ReceivedArray(x);
getchar();
}


///////////////////////////////////////////////////////////////


For passing 2D arrays (oops! some lines in spanish, sorry!):

(includes: iostream, stdlb, stdio and math)


/////////////////////////////////////////////////

using namespace std;

void ver(int x[][20]){
for(int i=0; i<15; i++)  {
  for(int j=0; j<20; j++) {
   cout<< x[i][j] <<" ";       }
   cout << "\n";        }

}

void cambiar0(int x[][20]){ int n[255];
   for (int i=255; i>=0; i--)
    n[255-i]=i;


for(int i=0; i<15; i++)
  for(int j=0; j<20; j++)
      for(int k=0; k<255; k++)
       if(x[i][j]==n[k])  {
          x[i][j]=k; break;  }  
}

int main(int argc, char* argv[]){
int x[15][20]; char a; 

for(int i=0; i<15; i++)
  for(int j=0; j<20; j++)
   x[i][j]=rand()%255;

  cout << "¿desea ver la matriz? s/n ";
 cin >> a;
 if(a=='s') ver(x);

 cambiar0(x);

 cout << "\n\n";
 cout << "¿desea ver la matriz? s/n ";
 cin >> a;
 if(a=='s') ver(x);

system("PAUSE"); return 0;
}

///////////////////////////////////

Hope this is what you meant.

希望这就是你的意思。

#7


arr is a pointer to the multi-dimesional array you have and is actually a pointer to an int. Now since your function accepts a pointer to an int pointer, you need to get the address of arr using: &arr and pass that to the function so that you will have this code:

arr是指向你所拥有的多维数组的指针,实际上是指向int的指针。现在,由于你的函数接受一个指向int指针的指针,你需要使用:&arr获取arr的地址并将其传递给函数,以便你拥有这个代码:

To coerce the array: Pass &arr to the function. To reference the array inside the func: *maze[x][y]

强制数组:传递和arr到函数。引用func中的数组:* maze [x] [y]