C++动态内存分配.将动态分配的 char* 返回变量数组分配给 char 变量

C++ Dynamic Memory Allocation. Assigning a Dynamically allocated array of char* return variable to a char variable?

本文关键字:变量 char 分配 返回 数组 动态 内存 动态分配 C++      更新时间:2023-10-16

所以我正在尝试添加一个动态分配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());
}