C:char指针数组没有发挥预期的动态 [英] C: array of char pointers not working as expected dynamically

查看:172
本文介绍了C:char指针数组没有发挥预期的动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的code下面的代码片段,我想使用动态分配的的char * 数组来保存字符串从标准输入到来。

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

我使用的是临时的静态数组首先存储从标准输入,然后根据一定的条件下将其复制到字符数组的字符串* 。我在运行时内存分配到个人的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);

所以 no_of_ref 持有终于收到字符串总数。例如20,但是,当我打印整个参考阵列看到每个字符串,我得到的排在最后,得到印刷20次。相同的字符串

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.

推荐答案

下面的code的引入问题:

Here of your code introduces the problem:

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

这是因为在C指针分配影响指针和指针只,不会做它的内容什么。您应该使用之类的东西的memcpy 的strcpy

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;

这篇关于C:char指针数组没有发挥预期的动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆