简体   繁体   English

如何删除和重新分配动态分配的指针

[英]How to delete and reassign a dynamically allocated pointer

I'm taking a c++ programming course (we are still mostly using C) and we just got to dynamic allocation of memory. For one of my homeworks, I'm asked to create a function that transposes any given matrix.我正在参加 c++ 编程课程(我们仍然主要使用 C),我们刚刚开始动态分配 memory。对于我的一项家庭作业,我被要求创建一个 function 来转置任何给定的矩阵。 This function is given the following arguments as inputs: a pointer, in which are saved the matrix elements, the number of rows and of colunms.这个 function 被赋予以下 arguments 作为输入:一个指针,其中保存了矩阵元素、行数和列数。 I would like this to be a void type function that changes the order of the stored elements without returning any new pointer.我希望这是一个void类型 function,它可以在不返回任何新指针的情况下更改存储元素的顺序。 I tried creating a new pointer, in which I save the elemtens in the correct order (using 2 for loops).我尝试创建一个新指针,在其中我以正确的顺序保存元素(使用 2 个for循环)。 Then what I would like to do is deallocating the original pointer (using the delete command), assinging it to the new pointer and finally deleting the new pointer.然后我想做的是释放原始指针(使用delete命令),将其分配给新指针,最后删除新指针。 This unfortunately does not work (some elements turn out to be random numbers), but I don't understand why.不幸的是,这不起作用(某些元素原来是随机数),但我不明白为什么。 I hope my code is more precise and clear than my explanation:我希望我的代码比我的解释更精确和清晰:

void Traspose(float *matrix, const int rows, const int cols ){

    auto *tras = new float [rows * cols];
    int  k = 0;

    for(int i = 0; i < cols; i++){
        for(int j = 0; j < rows * cols; j += cols){
            tras[k] = matrix[j + i];
            k++;
        }
    }

    delete[] matrix;
    matrix = tras;
    delete[] tras;
}

All those lines are wrong:所有这些行都是错误的:

delete[] matrix;
matrix = tras;
delete[] tras;
  1. You didn't allocate matrix so you don't want do delete it.您没有分配matrix ,所以您不想删除它。
  2. You assign tras to matrix and then you delete tras , after that, tras points nowhere, nor does matrix .您将tras分配给matrix ,然后delete tras ,之后, tras无处可去, matrix也没有。
  3. matrix = tras is pointless anyway, because matrix is a local variable, and any changes to local variables are lost after the function ends. matrix = tras无论如何是没有意义的,因为matrix是一个局部变量,并且在 function 结束后对局部变量的任何更改都将丢失。

You're inventing a problem where none should exist.您正在发明一个不应该存在的问题。

A matrix AxB in dimension will transpose to a matrix BxA in size.尺寸为 AxB 的矩阵将转置为尺寸为 BxA 的矩阵。 While the dimensional difference is obvious the storage requirements might not be so.虽然尺寸差异很明显,但存储要求可能并非如此。 Your storage is identical.您的存储是相同的。

Per the function signature, the change must be done in the same memory allocated to matrix .根据 function 签名,更改必须在分配给matrix的同一个 memory 中完成。 Eg, the results should be stored back into matrix memory. So, don't delete that memory;例如,结果应该存储回matrix memory。所以,不要删除那个 memory; leave it alone.不要管它。 It is both large enough to hold the transposition, and owned by the caller regardless.它既足够大以容纳换位,又无论如何都归调用者所有。

Rather, do this:相反,这样做:

void Traspose(float *matrix, const int rows, const int cols)
{
    float *tras = new float[ rows * cols ];
    int k = 0;

    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows * cols; j += cols)
            tras[k++] = matrix[j + i];
    }

    for (int i=0; i<k; ++i)
        matrix[i] = tras[i];

    delete [] tras;
}

Note this gets quite a bit simpler (and safer) if the option to use the standard library algorithms and containers is on the table:请注意,如果使用标准库算法和容器的选项在桌面上,这会变得更简单(也更安全):

void Traspose(float *matrix, const int rows, const int cols)
{
    std::vector<float> tras;
    tras.reserve(rows*cols);

    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows * cols; j += cols)
            tras.emplace_back(matrix[j + i]);
    }
    std::copy(tras.begin(), tras.end(), matrix);
}

Finally, probably worth investigating in your spare time, there are algorithms to do this, even for non-square matrices, in place without temporary storage using permutation chains .最后,可能值得在业余时间研究一下,有一些算法可以做到这一点,即使对于非方阵,也可以在没有临时存储的情况下使用置换链 I'll leave researching those as an exercise to the OP.我将把研究这些作为练习留给 OP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM