C 指向数组的指针

C 指向数组的指针,c,arrays,pointers,C,Arrays,Pointers,我读过那些文章 我想进一步解释一下发生了什么 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 do

我读过那些文章

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

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?
哪些是正确的,哪些是错误的,以及原因

在关于2d数组(实际上只是1d数组)的文章中,他写道:

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)
它们之间的区别是什么?为什么它们都有效


如果您能详细解释后面发生的事情,我将不胜感激。我希望问题能够澄清。

函数参数声明

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 */
相当于

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()
。特别注意指针。这意味着在
bar()
内,
sizeof(arr)
将始终是
sizeof(int*)
,而不是
sizeof(int[5])
sizeof(int[3])

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

问题1)

  • 编译器会告诉您,
    void bar(int arr*[3],…)
    无效
  • *
    移动到前面将给出
    无效条(int*arr[3],…)
    ,它是
    int*
    的数组,并转换为指向指针的指针:
    int**arr
  • 这不同于
    空栏(int arr[][3],…)
    ,它是指向3个int数组的指针或指向第二维度为3的多维数组的指针
问题2)

  • 这两者之间没有区别。两者都是指向上面问题1中的3个整数数组的指针
进一步阅读


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

您可以将其输入.c文件并编译。编译器将判断它是否正确。紧接着第二个代码块:“哪个将是指向传递的数组的第一个元素的指针…”这是不准确的
d
是指针变量(在本例中也是参数变量)。它有一个地址。无论该地址引用数组的底部、单个
int
,甚至是NULL,都不能断定它是指向数组第一个元素的指针。@WhozCraig如果我传递给它:int I[2]={0,1},它将是指向I的第一个元素的指针。是的,如果传递它。仅仅查看原型而不知道从调用方传递了什么,您无法推断出除了您已获得地址之外的任何内容。这实际上是我的观点。调用方可以知道它是一个数组,但函数(被调用方)中的代码没有强制要求它实际上是一个数组。int(*p)[4]是一个指针数组,而不是指向数组的指针。关于这一点,一个重要的注意事项是:无论通过哪种方式传递,都会丢失数组的大小信息。因此,不可能通过
sizeof(array)
获得数组的大小。同样重要的是,裸数组参数的前导下标大小实际上被忽略<就编译器而言,code>ar[4][5]与
ar[][5]
相同。正如
ar[n]
实际上是
ar[]
.void bar(int(*arr)[4]),这是一个指向数组的指针,它和你的数组有什么区别?@AR89参数
int(*arr)[4]
int arr[][4]
@AR89当你有多维数组时,就这样声明它。使用
int-arr[][3]
int(*arr)[3]
,但不要使用
int*arr
。您当然可以将其解释为
arr[i*3+j]
,但我不推荐这样做。更好地使用
arr[i][j]