将std :: list转换为char * [size] [英] Converting a std::list to char*[size]

查看:64
本文介绍了将std :: list转换为char * [size]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我无法解释,字符数组中的每个项目...都等于添加到它的最后一个项目...例如,progArgs [0]到progArgs [size]包含最后一个项目的值

for some reason I cannot explain, every single item in the character array...is equal to the last item added to it...for example progArgs[0] through progArgs[size] contains the value of the last item.

我无法弄清楚自己一生中做错了什么.有什么建议吗?

I cannot figure out what I'm doing wrong for the life of me. Any suggestions?

int count = 0;
char *progArgs[commandList.size()]

    for(list<string>::iterator t=commandList.begin(); t!=commandList.end(); t++)
    {
        char item[strlen((*t).c_str())]; //create character string
        strcpy(item, (*t).c_str()); //convert from const char to char
        progArgs[count] = item;
        count++;
    }

感谢大家的快速反应...我明白您在说什么

Thanks for all the quick responses everyone...I see what you are talking about

推荐答案

您要为的每个元素分配相同的指针(堆栈数组 item 的第一个元素的地址)> progArgs ,然后反复覆盖该内存.您可以这样做:

You're assigning the same pointer (the address of the first element of the stack array item) to each element of progArgs, then repeatedly overwriting that memory. You can do:

progArgs[count] = strdup(t->c_str());

并删除for正文的前两行.

and get rid of the first two lines of the for body.

strdup 分配内存,因此稍后必须使用 free 释放每个元素.另外,您没有为NUL终止符分配字符.您需要 strlen +1.但是,这不是 strdup 的问题,因为它会为您分配.

strdup allocates memory, so you will have to free each element with free later. Also, you were not allocating a character for the NUL-terminator. You need would strlen + 1. However, this is not an issue with strdup, since it allocates for you.

这篇关于将std :: list转换为char * [size]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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