如何将字符**中的数据值复制到新字符**中
How to copy data values in char** into a new char**?
我正在做的事情:
你好。我目前有一个char**
变量,它是指向字符串数组的指针。我有一个循环,在这个循环中,char**
需要备份到结构向量。因此,该结构内部具有可变类型的字符**。
不幸的是,对于这件作品,我必须使用char**
类型。我无法使用char* vName[]
类型。
我的问题是什么:
我目前面临的问题是,当我添加新结构时,char**
指向所有结构中可用的最新数据,而不是最新的数据。
我尝试过的:
我尝试使用strcpy
、memcpy
和使用普通的旧值,但它们似乎不起作用。我试过使用newItem.storedVars[i] = newVars
但这似乎也不起作用。
如何获取或复制新char**
数组中的数据并将其存储到结构中,而不会被循环再次修改?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct StringHolder{
char** storedVars; //stored char** variable
};
int main(int argc, char *argv[]){
char** newVars; //stores current char** values
int counter = 100; //counter
vector<StringHolder> vectorOfStructs;
while(counter!=0){ //while counter is going downward
StringHolder newItem; //create a new string
char** storedVarsToAdd; //stored variables that I will be adding
newVars = externalVarsFetcher(); //get the new char** variable from the external function
storedVarsToAdd = newVars; //this statement doesn't work
//neither does this statement
for(int i = 0; i < 10; i++){
storedVarsToAdd[i] = newVars[i];
}
newItem.storedVars = storedVarsToAdd; //take the new item I created, update it's char** value with a new one
vectorOfStructs.push_back(newItem); //push the struct onto the vector
counter--; //continue through the array
}
}
你的问题是你只是在玩弄指针,你没有复制字符串。你应该使用std::string
,但这听起来像家庭作业,所以你可能被告知不要这样做。如果不是这种情况,请使用std::string
如果必须使用char**
等:
for(int i = 0; i < 10; i++){
storedVarsToAdd[i] = strdup(newVars[i]);
}
strdup
将为您分配内存并复制字符串。
现在您有潜在的内存泄漏,但这是一个不同的问题(提示 - 使用 std::string
(。
下面介绍如何存储命令行参数,这与您要执行的操作相同:
std::vector<std::string> args;
for (int i=0; i<argc; i++)
args.push_back(argv[i]);
相关文章:
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 从常量字符*、字符*参数到标准::字符串的直接转换接口
- 动态构造函数中的新字符 [] 抛出"损坏的顶部大小";
- C++ 中数组(单引号和双引号)的可视常量字符* 与字符
- 如何编写模板函数来创建给定常量字符*的字符/wchar_t字符串?
- 如何使字符*指向字符[]?
- char* = 新字符 和 char* = 新字符[N]
- 当我运行字符 * name1 = 新字符[ 6 ]时会发生什么;strcpy( 名称1, "Henry" );字符 * 名称 2 = 名称 1;名称1[0] = 'D';
- 如何将字符**中的数据值复制到新字符**中
- C++新字符[]的问题
- 新字符数组不会初始化为全部零
- 字符 [] 和新字符 [] 使用恒定长度时的区别
- 我使用构造函数(使用内存 Dinamic char *t = 新字符 [10] t = "test123456" ;))时遇到错误堆错误并在析构函数中删除 [] t;错误
- 如何将这个新字符**写入.bmp文件
- 新字符是否实际上保证类类型的对齐内存
- C++ 堆栈程序 指针问题的 Wsing 数组 新字符[len],其中 len 为 2 创建 16 个字符
- 错误的内存分配新字符 [N]
- 为什么你需要在新字符(str.length())上添加一个
- 将文本文件的内容一个字符一个字符地读入矢量,不跳过空白或新行
- 如何将字符指针数组拆分为两个带有分隔符的新字符指针数组