C 如何以2D数组的形式访问双指针类型参数?
大概是这样的:C 如何以2D数组的形式访问双指针类型参数?,c,arrays,C,Arrays,大概是这样的: struct s { int a; int b; } void f(struct s **a) { a[0][0].a = 0; // Access violation here } int main() { struct s a[5][3]; f(a); return(0); } 那么,如何使用2D数组表示法访问内部函数f的内容呢 像a[5][3]这样的数组连续存储struct实例,而struct s**a将连续存储指针,使
struct s
{
int a;
int b;
}
void f(struct s **a)
{
a[0][0].a = 0; // Access violation here
}
int main()
{
struct s a[5][3];
f(a);
return(0);
}
那么,如何使用2D数组表示法访问内部函数f的内容呢 像
a[5][3]
这样的数组连续存储struct
实例,而struct s**a
将连续存储指针,使每个指针指向struct s
的一个实例。因此struct s a[5][3]
(自动转换为指针)和struct s**a
是不兼容的指针,如果编译时带有警告,您就会知道这一点
一个简单的解决办法是
void f(struct s a[][3])
{
a[0][0].a = 0; // Access violation here
}
更好的解决方案是
#include <stdlib.h>
struct some_structure
{
int value1;
int value2;
};
void
set_value(struct some_structure **array, size_t row, size_t column)
{
array[row][column].value1 = 0;
array[row][column].value2 = 0;
}
int
main(void)
{
struct some_structure **array;
array = malloc(5 * sizeof(*array));
if (array == NULL)
return -1; // Allocation Failure
for (size_t i = 0 ; i < 5 ; ++i)
{
array[i] = malloc(sizeof(*(array[i])));
if (array[i] == NULL)
return -1; // Allocation Failure
}
set_value(array, 0, 0);
for (size_t i = 0 ; i < 5 ; ++i)
free(array[i]);
free(array);
return 0;
}
#包括
构造一些结构
{
int值1;
int值2;
};
无效的
设置值(结构某些结构**数组、大小行、大小列)
{
数组[行][列].value1=0;
数组[行][列].value2=0;
}
int
主(空)
{
struct some_结构**数组;
数组=malloc(5*sizeof(*数组));
if(数组==NULL)
return-1;//分配失败
对于(尺寸i=0;i<5;++i)
{
数组[i]=malloc(sizeof(*(数组[i]));
if(数组[i]==NULL)
return-1;//分配失败
}
设置_值(数组,0,0);
对于(尺寸i=0;i<5;++i)
自由(数组[i]);
自由(数组);
返回0;
}
正如我上面所说的,将存储指针,因为您需要为此分配内存,您可以像上面的示例一样使用
malloc()
。为什么不使用a
?指针不是数组,数组也不是指针@SouravGhosh我必须在手机上输入代码(并格式化),所以我尽量让它简单。很抱歉给您带来不便。