1
#include<stdio.h>
using namespace std;
void fun(int** a){}
int main()
{
    int n;
    scanf("%d",&n);
    int a[n][n];
    fun(a);
    return 0;
}

在 C++ 中出现此错误,但它在 C 中工作正常,但适用于类型转换为 (void*)a 然后转换为 array=(int**)a:

test_.cpp:9:8: error: cannot convert
   ‘int (*)[(((unsigned int)(((int)n) + -0x00000000000000001)) + 1)]’
to ‘int**’ for argument ‘1’ to ‘void fun(int**)’
tried to pass a[][size] but size is not known
4

4 回答 4

3

双精度数组不会转换为双指针。

将双精度数组传递给您的函数,如下所示:

void fun(int arr[][5]); 

现在它将起作用。

于 2013-03-30T13:43:56.207 回答
1

T[N][N]衰减时,它变成T*[N]在数组中传递时没有可行的转换。

于 2013-03-30T13:44:26.247 回答
1

将二维数组传递给函数时,您必须指定第二维大小。否则,编译器无法在不知道第二维大小的情况下对二维数组元素进行寻址。采用

f(a[][5]) 
于 2013-03-30T13:44:41.750 回答
1

您的代码有几个问题。一个是 C 语言,另一个是 C++。

The C problem:
Even in C, your multidimensional array int a[n][n] does not convert to an int**. There's a huge difference between ragged (or jagged) multidimensional arrays and contiguous multidimensional arrays. Ragged arrays are declared and allocated as

  • int ** jagged_array
    A jagged array declared in this style can obviously be passed as an int** argument to some function; there's no conversion involved. With this type of array, the programmer must allocate (and eventually free) storage for an array of int* pointers to each of the rows in the array and must also allocate (and eventually free) storage for each of the array's rows.

  • int * jagged_array[size_spec].
    A jagged array declared in this style can also be passed as an int** argument to some function because of the way arrays decay to pointers in C (and C++). With this type of array, the programmer must allocate (and eventually free) storage for each of the array's rows.

Note that in both forms, there is an explicit place in memory for the int* pointers that point to the zeroth elements of the rows of the array. That is not the case with multidimensional arrays. A pointer to a row in a multidimensional array is computed, not stored. A multidimensional array declared as int a[n][n] cannot decay to an int**. It instead decays into an int*[n]. In C, a function that receives a variable length multidimensional array such as your int a[n][n] should be declared as <return_type> fund (int n, int vla[n][n]). (The array argument could also be specified as vla[][n]; the outer dimension is not needed.)


The C++ problem:
You are using variable length arrays. C++ does not support that C99 concept. That concept didn't exist in C with the original 1998 version of C++. The 2003 C++ standard was a minor revision to the 1998 C++ standard, so it didn't jump to C99. The authors of the most recent C++ standard, C++11, explicitly rejected supporting those C99 variable length arrays. You can't use variable length arrays in C++, at least not portably.

于 2013-03-30T15:09:50.303 回答