如何将字符**中的数据值复制到新字符**中

How to copy data values in char** into a new char**?

本文关键字:字符 新字符 复制 数据      更新时间:2023-10-16

我正在做的事情:
你好。我目前有一个char**变量,它是指向字符串数组的指针。我有一个循环,在这个循环中,char**需要备份到结构向量。因此,该结构内部具有可变类型的字符**。
不幸的是,对于这件作品,我必须使用char**类型。我无法使用char* vName[]类型。

我的问题是什么:
我目前面临的问题是,当我添加新结构时,char**指向所有结构中可用的最新数据,而不是最新的数据。

我尝试过的:
我尝试使用strcpymemcpy 和使用普通的旧值,但它们似乎不起作用。我试过使用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]);