1

我已经阅读了这些文章http://eli.thegreenplace.net/2010/01/11/pointers-to-arrays-in-c/ http://eli.thegreenplace.net/2010/04/06/pointers- vs-arrays-in-c-part-2d/

我想进一步解释发生了什么。

int joe[] = {1, 2, 3, 4};

void test(int (*p)[4])

这是一个指向数组的指针,它不同于

void test(int *d);

这将是指向传递的数组的第一个元素的指针,或者是另一个指针的副本。我可不可以做?

*p = joe //I guess not, I'm obtaining the array passed, and I'm trying to reassign it (which can't be done)
d = joe //I guess not, but I would like to know what would happen to d
*d = joe //Same as above
d = &joe //I'm giving to d the address of joe, what will it be?

哪些是正确的,哪些是错误的,以及为什么。

在关于二维数组(实际上只是一维数组)的文章中,他写道:

void bar(int arr[2][3], int m, int n)
void bar(int arr[][3], int m, int n)
void bar(int (*arr)[3], int m, int n)

都是正确的。

1)问题:

void bar(int arr[][3], int m, int n)
void bar(int arr*[3], int m, int n)

是相同的?如果不是,它们之间有什么区别?

2)问题:

 void bar(int arr[][3], int m, int n)
 void bar(int (*arr)[3], int m, int n)

它们之间有什么区别,为什么它们都有效?

我非常感谢详细解释背后发生的事情,我希望问题很清楚。

4

1 回答 1

3

函数参数声明

void bar(int arr[]); /* this is a pointer to int */

相当于

void bar(int arr[5]); /* this is a pointer to int, compiler just ignores 5 */

相当于

void bar(int *arr); /* this is a pointer to int */

在所有情况下,都会将指向 int 的指针指向int数组的指针提供给bar(). 特别注意指针。这意味着 inside bar(), sizeof(arr)will always be sizeof(int*), neversizeof(int[5])sizeof(int[3])例如。

其余的,包括多维数组,都遵循这个简单的规则。

问题1)

  • 编译器会告诉你,这void bar(int arr*[3], ...)是无效的。
  • 移到*前面会给出void bar(int *arr[3], ...),它是一个数组,int*并转换为指向指针的指针:int **arr
  • 这与 不同void bar(int arr[][3], ...),后者是指向 3 个整数数组的指针或指向第二维为 3 的多维数组的指针。

问题2)

  • 这两者没有区别。两者都是指向 3 个整数数组的指针,如上面的问题 1 所示。

来自google的进一步阅读:解释c声明

最后一个建议:不要害羞并使用编译器。它会告诉您您的代码是否有效。

于 2012-11-23T10:59:55.863 回答