【问题标题】:c: issues when allocating 2d char array dynamically?c:动态分配二维字符数组时出现问题?
【发布时间】:2014-05-02 11:18:54
【问题描述】:

我正在尝试分配一个 2D 字符数组,以便像 ary[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" );
    //......
}

不幸的是,这会导致某处溢出,并且程序在执行中存在错误,我从这里获得了一些关于动态分配的参考:http://staff.science.nus.edu.sg/~phywjs/CZ1102/lecture20/sld014.htm

我想知道这里出了什么问题以及如何解决这个问题,谢谢。

【问题讨论】:

  • calloc 使用的参数顺序相反,从herethere 可以看出;虽然我真的不知道它是否会导致错误的行为。
  • @ThoAppelsin calloc 的参数顺序在我所知道的任何平台上都无关紧要。

标签: c arrays dynamic-allocation


【解决方案1】:

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

代替

*vals = (char**) calloc( sizeof( char** ), valscount );

使用

*vals = (char**) calloc( sizeof( char* ), valscount );

代替

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

使用

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

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

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

【讨论】:

  • 您可以通过使用成语避免这些错误:P = calloc(N, sizeof *P);,例如*vals = calloc( valscount, sizeof **vals );
【解决方案2】:

您的运算符优先级错误:*vals[i] 的计算结果为 *(vals[i]),而不是 (*vals)[i]。详情请见http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

解决方法是将*vals[i] 更改为(*vals)[i]

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

【讨论】:

  • 是的!就是这样,现在问题解决了,精度很重要!谢谢你!
猜你喜欢
  • 2021-03-25
  • 1970-01-01
  • 2017-03-11
  • 2021-01-02
  • 1970-01-01
  • 2021-02-03
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多