我在C中有一个固定长度的二维数组,
如何为它分配内存,以便我可以使用它
超出功能范围? (当尝试使用malloc/calloc
编译器时
说you cant convert void* / char** to char[FIXED][FIXED]
)
[评论更新:]
所以我只想说出我要做的事情:
我编写的函数应该返回它创建的2D数组的列表(实现为结构),但是因为它们是作为局部变量创建的,所以它们“死”并且之后无法返回/到达
答案 0 :(得分:1)
您可以为具有C VLA的数组分配动态内存(char **
的类型错误):
int nrows, ncols;
char (*array)[ncols] = malloc(ncols * nrows);
答案 1 :(得分:1)
正如您所注意到的,数组不是指针 特别是,数组数组不是指针的指针 (要清楚地看到这一点,请在纸上画出来。)
但是,在某些上下文中,数组会隐式转换为指向其第一个元素的指针,例如当作为参数传递给函数或从函数返回时。
因此,可以将数组数组转换为指向数组的指针:
int a[3][4];
int (*b)[4] = a; /* b is a pointer to an array of four elements - the first element of a */
从一个函数中返回一个(这个是一个乱七八糟的东西):
int (*make_stuff(size_t size))[4]
{
return malloc(size * sizeof(int[4]));
}
但整个指针到数组的语法非常混乱且难以理解,几乎不可能正确 如果你使用typedef,我个人觉得这些更易读:
typedef int row[4];
row a[3];
row *b = a;
row *c = malloc(3 * sizeof(row));
row* make_stuff(size_t size)
{
return malloc(size * sizeof(row));
}
答案 2 :(得分:0)
固定长度的数组存储在自动存储器中,即Stack保留在功能范围内。要将变量存储在堆存储中,必须使用malloc / calloc动态分配内存。
例如(2D数组)
// N x M array
char **a = malloc( sizeof *a * N ) ;
if( a == NULL )
{
// Error allocating memory
return -1 ;
}
for( i = 0; i < N; i++ )
{
a[i] = malloc( sizeof * a[i] * M ) ;
}
例如(1D数组),
void SomeFunc( void )
{
char a[10] ; // will be stored in stack (function scope)
char *b ; // declare a pointer that points to char memory.
b = malloc( 10 * sizeof(char) ) ;
if( b == NULL )
{
// Error in allocating memory
return -1 ;
}
// will be stored in Heap (scope = till you free the memory)
//... Your code goes here...
//... Call to other functions
free( b ) ;
}
此外,如果您不想使用global
,则可以将其设为static
或malloc/calloc
。
例如:
char a[10] = {0} ; // Global variable, stored in Data segment
void SomeFunc( void )
{
static char b[10] = {0} ; // static variable, stored in Data segment
}
存储在数据段中的变量的范围将贯穿执行。因此,即使在SomeFunc()