gpt4 book ai didi

c - 编写一个接受所有 int 类型的二维数组作为参数的函数签名,无论用户选择哪种方法?

转载 作者:行者123 更新时间:2023-11-30 20:11:56 25 4
gpt4 key购买 nike

举例说明:

#include <stdlib.h>
#include<stdio.h>

void simple_function(int s , int array[][s]);

int main(void){

int x;
/*Static 2D Array*/
int array[2][2];

/*Many Methods to Dynamically Allocate 2D Array....for example*/

/* Using Array of pointers*/
int *array1[2];
for(x=0;x<2;x++){array1[x] = calloc (2, sizeof(int));}

/*Using pointer to a pointer */
int **array2 = calloc (2, sizeof(int*));
for(x=0;x<2;x++){array2[x] = calloc (2, sizeof(int));}

/*Using a single pointer*/
int *array3 = calloc (4 , sizeof(int));



/* Codes To Fill The Arrays*/


/*Passing the Arrays to the function, some of them won't work*/
simple_function(2, array); /*Case 1*/
simple_function(2, array1); /*Case 2*/
simple_function(2, array2); /*Case 3*/
simple_function(2, array3); /*Case 4*/

return 0;
}


void simple_function (int s, int array[][s]){

int x,y;

for(x=0;x<s;x++){
for(y=0;y<s; y++){
printf ("Content is %d\n", array[x][y]);
}
}
}

我的问题:有没有办法编写 simple_function 的签名,让它接受所有情况,无论用户选择哪种方法?如果没有,如果我想制作一个库,该功能最优选的是什么?

最佳答案

您实际上声明了两种不同类型的对象,如下所示

enter image description here

您的 arrayarray3 均以 4 个连续的 int 形式存储在内存中。没有其他信息,您只需为 4 个整数保留空间,并且 C 规范要求它们是连续的。

但是,array1array2实际上是指针数组。您的代码为两个指针的数组保留内存,每个指针都指向两个int 的数组。 int 将按两个一组排列,但这些组可以分散在内存中的任何位置。

由此可见,编译器不能使用相同的代码来访问两种类型的数组。例如,假设您正在尝试访问 array[x][y] 处的项目。对于连续数组,编译器会像这样计算该项目的地址

address = array + (x * s + y) * sizeof(int)

对于分散数组,编译器会像这样计算地址

pointer = the value at {array + x * sizeof(int *)}
address = pointer + y * sizeof(int)

因此您需要两个函数来处理这两种情况。对于连续数组,函数如下所示

void showContiguousArray( int s, int array[][s] )
{
for ( int x=0; x<s; x++ )
for ( int y=0; y<s; y++ )
printf( "array[%d][%d] = %d\n", x, y, array[x][y] );
}

对于分散数组,函数为

void showScatteredArray( int s, int **array )
{
for ( int x=0; x<s; x++ )
for ( int y=0; y<s; y++ )
printf( "array[%d][%d] = %d\n", x, y, array[x][y] );
}

请注意,这些函数是相同的,除了一件事,数组参数的类型。编译器需要知道类型才能生成正确的代码。

如果该数组在其使用的相同范围内声明,那么所有这些详细信息都会被隐藏,并且您似乎正在使用完全相同的代码访问不同类型的数组。但这只能起作用,因为编译器从早期的声明中知道了数组的类型。但如果要将数组传递给函数,则必须在函数声明中显式指定类型信息。

关于c - 编写一个接受所有 int 类型的二维数组作为参数的函数签名,无论用户选择哪种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38446645/

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