gpt4 book ai didi

c++ - 如何将 char** 中的数据值复制到新的 char** 中?

转载 作者:行者123 更新时间:2023-11-27 22:46:34 24 4
gpt4 key购买 nike

我在做什么:
你好。我目前有一个 char** 变量,它是一个指向字符串数组的指针。我有一个循环发生,在这个循环中 char** 需要备份到一个结构 vector 。所以结构体内部有一个变量类型 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)。

关于c++ - 如何将 char** 中的数据值复制到新的 char** 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42126995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com