C: array of char pointers not working as expected dynamically

旧城冷巷雨未停 提交于 2019-12-24 12:14:15

问题


I have the below snippets from my code where I am trying to use a dynamically allocated char * array to hold strings coming from stdin.

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

I am using a temporary static array to first store the string from stdin, then based on a certain condition copy it to the array of char * . I am allocating memory to individual char * in runtime.

                        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);

so no_of_ref holds the total number of strings finally received. e.g 20. But when I print the whole reference array to see each string, I get the same string that came last , getting printed 20 times.


回答1:


Here of your code introduces the problem:

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

That's because assignment of pointers in C affects pointers and only pointers, which won't do anything with its contents. You shall use things like memcpy or strcpy:

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


来源:https://stackoverflow.com/questions/19761453/c-array-of-char-pointers-not-working-as-expected-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!