gpt4 book ai didi

c - 指向数组的指针

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

我读过那些文章 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)

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

我真的很感激能详细解释背后发生的事情,我希望问题是清楚的。

最佳答案

函数参数声明

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]) 例如。

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

问题一)

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

问题2)

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

进一步阅读 google: interpret c declaration

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

关于c - 指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13527600/

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