【问题标题】:C: array of char pointers not working as expected dynamicallyC: char 指针数组未按预期动态工作
【发布时间】:2013-11-04 04:02:57
【问题描述】:

我的代码中有以下 sn-ps,我试图使用动态分配的 char * 数组来保存来自标准输入的字符串。

char **reference
reference = calloc(CHUNK, sizeof(char *));

我使用一个临时的静态数组先存储来自stdin的字符串,然后根据一定的条件将它复制到char *的数组中。我在运行时将内存分配给个人char *

                        reference[no_of_ref]=malloc(strlen(temp_in) + 1);
                        reference[no_of_ref++]=temp_in;
//                   printf(" in temp : %s , Value : %s   , Address of charp : %p\n",temp_in,reference[no_of_ref-1],reference[no_of_ref-1]);
                        memset(&temp_in,'\0',sizeof(temp_in));
                        pre_pip = -1;
                }

        /*If allocated buffer is at brim, extend it by CHUNK bytes*/
                if(no_of_ref == CHUNK - 2)
                        realloc(reference,no_of_ref + CHUNK);

所以no_of_ref 保存了最终收到的字符串总数。例如 20。但是当我打印整个 reference 数组以查看每个字符串时,我得到了最后一个相同的字符串,打印了 20 次。

【问题讨论】:

    标签: c arrays realloc char-pointer


    【解决方案1】:

    您的代码在这里介绍了问题:

    reference[no_of_ref]=malloc(strlen(temp_in) + 1);
    reference[no_of_ref++]=temp_in;
    

    这是因为 C 中的指针赋值会影响指针,并且只会影响指针,它不会对其内容做任何事情。你应该使用memcpystrcpy之类的东西:

    reference[no_of_ref]=malloc(strlen(temp_in) + 1);
    strcpy(reference[no_of_ref], temp_in);
    no_of_ref+=1;
    

    【讨论】:

    • 呸...这是我所知道的,但每次我使用 char * 复制时仍然会忘记。谢谢你再次提醒..!!
    • @DiwakarSharma 很高兴为您提供帮助 :)
    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2021-01-26
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多