gpt4 book ai didi

c - 将 C 数组传递给函数

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

我正在尝试理解 C 语言中的指针,我认为到目前为止我的理解还不错。我试图理解数组以及它们是如何传递给函数的。据我了解,当将数组传递给函数时,它是通过引用传递的,而当将数组传递给函数时,它指向内存中数组的开头或数组的第一个内存地址。所以如果我像这样创建一个数组:

char* arr[2] = {"Andrew", "Schools"};

我可以定义以下函数来接受这个数组,它实际上将指针传递给数组中的第一项:

void readSingleArray(char* arr[], int count) {
for(int i=0; i<count; i++) {
printf("%s\n", arr[i]);
}
}

void readSingleArray2(char** arr, int count) {
for(int i=0; i<count; i++) {
printf("%s\n", arr[i]);
}
}

第二个函数接受 char** arr 而不是 char* []。所以我是这样理解的:因为我有一个指针数组,所以这告诉编译器我想访问一个指向 char 的指针,所以任何一种方式都可以。

现在如果我像这样定义一个多维数组:

char* arr2[2][2] = {{"Andrew", "Schools"},{"Computer", "Programmer"}};

我可以定义以下函数:

void readMultiDimArray(char* arr[2][2], int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}

但不是这个函数:

void readMultiDimArray2(char** arr, int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}

我读到多维数组实际上是一维数组或一个内存块,编译器将弄清楚如何访问适当的数组项:How to pass a multidimensional array to a function in C and C++ .这对我来说很有意义所以我的问题是:为什么我可以对单个数组使用 char** arr 但在使用多维数组时这不会工作。因为我怎么看,无论如何,我只需要访问数组的第一个内存地址,因为它总是一个连续的位 block

最佳答案

这些函数声明

void readMultiDimArray(char* arr[2][2], int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}

void readMultiDimArray2(char** arr, int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}

不等价,如果您要传递一个声明为 char* arr2[2][2]; 的数组作为函数的参数,则第二个函数声明是错误的。正确的函数声明至少看起来像

void readMultiDimArray2( char * ( *arr )[2], int count, int count2) {
for(int i=0; i<count; i++) {
for(int x=0; x<count2; x++) {
printf("%s\n", arr[i][x]);
}
}
}

如果你有一个像这样声明的数组

T array[N];

where T some type 然后当数组传递给具有相同参数声明的函数时,它被转换为指向其第一个元素的指针。那就是它将有类型

T *ptr;

所以如果你有一个像这样声明的数组

char* arr2[2][2];

那么你可以通过下面的方式重新声明它

typedef char * T[2];

T arr2[2];

根据上面的解释会转换成这样

T *ptr;

何时将其作为参数传递。

现在用 T 代替它的实际类型,你会得到

char * ( *ptr )[2];

其中char *[2]是数组arr2的元素类型

每个二维数组实际上是一个一维数组,其元素又是一维数组。即它是一个数组的数组。

关于c - 将 C 数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685329/

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