Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c:动态分配2d字符数组时出现的问题?_C_Arrays_Dynamic Allocation - Fatal编程技术网

c:动态分配2d字符数组时出现的问题?

c:动态分配2d字符数组时出现的问题?,c,arrays,dynamic-allocation,C,Arrays,Dynamic Allocation,我正试图分配一个2D字符数组来访问,如ari[I][j],使用以下代码: #define stringmaxlen 20 void do_alloc( char ***vals, int valscount ){ *vals = (char**) calloc( sizeof( char** ), valscount ); int i = 0; for ( ; i<valscount; i++ ) *vals[i] = (char*) calloc

我正试图分配一个2D字符数组来访问,如
ari[I][j]
,使用以下代码:

#define stringmaxlen 20

void do_alloc( char ***vals, int valscount ){
    *vals = (char**) calloc( sizeof( char** ), valscount );
    int i = 0;
    for ( ; i<valscount; i++ )
        *vals[i] = (char*) calloc( sizeof( char* ), stringmaxlen );
}

int main( ){
    //......
    char** ary;
    do_alloc( &ary, 10 );
    strcpy( ary[0], "test" );
    //......
}
#定义stringmaxlen 20
void do_alloc(字符***VAL,整数VALCOUNT){
*VAL=(char**)calloc(sizeof(char**),VALCount);
int i=0;

对于(;i运算符优先级错误:
*vals[i]
的计算结果为
*(vals[i])
,而不是
(*vals)[i]
。有关详细信息,请参阅

修复方法是将
*vals[i]
更改为
(*vals)[i]


另外,分配
*vals[i]=(char*)calloc(sizeof(char*),stringmaxlen);
是错误的。它分配了太多的内存,因为它为
stringmaxlen
指针分配了空间,但您只需要
stringmaxlen
字符。

我想在cmaster的答案中添加以下内容

而不是

*vals = (char**) calloc( sizeof( char** ), valscount );
    (*vals)[i] = (char*) calloc( sizeof(char*), stringmaxlen );
使用

而不是

*vals = (char**) calloc( sizeof( char** ), valscount );
    (*vals)[i] = (char*) calloc( sizeof(char*), stringmaxlen );
使用

在第一种情况下,分配的内存大小没有变化,因为
sizeof(char**)
sizeof(char*)
相同。但是,第二种情况并非如此。
sizeof(char)
为1,而
sizeof(char*)
更大,32位硬件为4,64位硬件为8


更重要的是,它澄清了意图——您希望为
stringmaxlen
字符分配内存,而不是
stringmaxlen
指向字符的指针。

您用于
calloc
的参数的顺序与您从和中看到的相反;尽管我不知道这是否会导致错误行为。@在我所知道的任何平台上,
calloc
的参数顺序似乎都是不相关的。是的!就是这样,现在问题已经解决了,精度很重要!谢谢你!你可以用这个成语来避免这些错误:
P=calloc(N,sizeof*P);
,例如
*vals=calloc(valcount,sizeof**vals);
等。