C++动态内存分配.将动态分配的 char* 返回变量数组分配给 char 变量
C++ Dynamic Memory Allocation. Assigning a Dynamically allocated array of char* return variable to a char variable?
所以我正在尝试添加一个动态分配char*
,该是从名为
GetFileInputFromUser();
我为过程中的返回变量动态分配内存。
char* pstrReturnValue;
// Prime the loop
cout << "please enter a file location on your local machine (type 1 for default location) ";
cin >> strFileInputFromUser;
// Default location?
if (*(strFileInputFromUser + intIndex) == '1')
{
// yes, Get the length
intLength = strlen(strDefaultFileLocation);
// Allocate memory
pstrReturnValue = new char[intLength];
// copy default location in
for (intIndex = 0; intIndex <= intLength; intIndex += 1)
{
*(pstrReturnValue + intIndex) = *(strDefaultFileLocation + intIndex);
}
return pstrReturnValue;
我需要的是将返回变量添加到另一个字符数组(动态分配)。
void main()
{
bool blnResult = false;
ifstream ifsDataFile;
udtNodeType* pudtHeadNode = 0;
udtNodeType* pudtCurrentNode = 0;
udtNodeType* pudtNextNode = 0;
char* strFile;
udtNodeType udtReturnNode;
// Get the file path
strFile = GetFileInputFromUser();
blnResult = OpenFile(strFile, ifsDataFile);
// was it successful?
if (blnResult == true)
{
// Yes
// populate the list and, return the top node
udtReturnNode = *PopulateList(pudtNextNode, pudtCurrentNode, pudtHeadNode, &ifsDataFile);
// All done, close the file
ifsDataFile.close();
delete[] strFile;
// Delete the list
DeleteList(pudtNextNode, pudtCurrentNode, pudtHeadNode);
// Delete proof
PrintList(pudtNextNode, pudtCurrentNode, pudtHeadNode);
}
system("pause");
}
这是一个练习,根据要求,GetFileInputFromUser()
必须char*
它必须返回该指针,并且我必须在处置 LinkedList 之前删除该指针。我的事情是这样的,我知道如何动态分配内存,我知道如何删除所述内存,我的问题是我不能只为静态分配的char[]
赋值,我不能循环返回值来分配它,因为我必须能够将返回值变成某物。
我尝试将char* GetFileInputFromUser()
更改为char& GetFileInputFromUser()
,希望我能在内存中的位置获取地址,看看我是否可以希望以这种方式以某种方式取消引用返回值。
如果你注释掉delete[] strFile
并运行它,它运行良好,但我正在泄漏内存,这在我看来是不好的。我知道有一种方法可以做到这一点,但谷歌没有帮助,我从昨晚凌晨 1 点开始就一直被困在这个问题上。
谢谢大家的帮助。
如果我理解正确,您想将一个字符串添加到另一个字符串中。正确?如果是这样,你可以使用 strcat()。
谢谢Askarali,你让我走上了正确的道路,下面的代码是获得所需结果所需的代码,而不会得到损坏的堆异常。谢谢
void main()
{
char* strFile;
strFile = new char[50];
// Get the file path
strcpy(strFile, GetFileInputFromUser());
}
相关文章:
- 在C++中将变量 wstring 分配给 Char 数组
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 如何更好地检查两个 char 变量是否在一组值中?
- 将双精度值转换为 char 变量时字符串流如何工作
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- C++ 如何检查 char 变量是否未定义(未初始化)
- 如何将整数分配给 char 类型的变量
- 在 c++ 中将 Char 数组添加到 Char * 变量
- 如何正确地检查变量char中包含的字母
- char指针或char变量的默认值是多少
- 当对字符变量使用toupper()时,所述char变量输出多个字符.我该如何防止这种情况发生
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 声明具有两种类型的变量:"int char"
- 程序的执行在 C++ 中输入 char 变量后结束
- 如何创建一个 char *[] 变量,以便将其传递给函数
- 如何初始化类的 char 成员变量?
- LLVM-如何将ConstantExpr转换为ConstantDataArray,以便打印全局变量char*的值
- C++如何将变量char数组从一个函数传递到另一个函数