【问题标题】:Is there a best practice for allocating memory in C?是否有在 C 中分配内存的最佳实践?
【发布时间】:2015-06-21 00:42:20
【问题描述】:

我一直在尝试通过创建一个新的组合矩阵来创建一个将矩阵 B 附加到矩阵 A 上的函数。我创建的第一个函数将一个指针(在 main() 中声明)传递给该函数,然后该函数处理该指针以添加值。这行得通。但是,我也在尝试一种不同的方法,方法是在函数中使用 malloc() 来定义一个指针,以便函数更便携和动态。但是,当我尝试在最终矩阵中打印最终值时,我得到了未定义的行为。

这是创建的头文件中包含的函数。

#include <stdio.h>
#include <stdlib.h>

  int *fAddArrays(int *A, int *B, int a, int b)
{
    
    int *O;
    O = (int *) malloc((a+b) * sizeof(int));
    
    int c;
    int d;
    
    for (c = 0; c < a; c++)
    {
        *O = *A;
        A++;
        O++;
        
    }
    
    for (d = 0; d < b; d++)
    {
        *O = *B;
        B++;
        O++;
    }
    
    
        return O;
}

这里是main()中函数的使用

#include <stdio.h>
#include <unistd.h>
#include "CustomArray.h"
#include <stdlib.h>


int main(void)

{
    int A[5] = {1,2,3,4,5};
    int B[7] = {6,7,8,9,10,11,12};
    int a = 5;
    int b = 7;
    int c = a + b;
    int x = 0;
    int NewArray[c], *ArrayPtr;
    
    ArrayPtr = fAddArrays(A,B,a,b);

    for( x = 0; x < c; x++)
    {
        *(NewArray + x) = *ArrayPtr;
        
        printf("Value of NewArray[%d] = %d\n", x, *ArrayPtr);
        sleep(1);
        
        ArrayPtr++;
    }
    
    
    
    return 0;
}

【问题讨论】:

  • 不要将变量命名为O,它看起来非常像0。而return 0return O在这段代码中的含义很不一样...
  • return O; : O 与 malloc 的返回不同,因为 O++;
  • 一个问题是你没有抓住 malloc 的返回值,所以释放它会很困难
  • 啊^ 谢谢。我忘了我做了O ++。 @MichaelAnderson,我知道我不应该使用 O,这很混乱,会改变它。
  • @JCodder int NewArray[c] 这不是有效的 C++(您已将问题标记为 C++)。如果是C++,那么std::vector&lt;int&gt; 的使用将/可以/应该代替malloc

标签: c pointers matrix


【解决方案1】:

你的问题是你增加 O 然后返回它。

您需要保存原始值并增加一个副本。

int *fAddArrays(int *A, int *B, int a, int b) {

    int * original = (int *) malloc((a+b) * sizeof(int));
    int * p = original;

    for (int c = 0; c < a; c++) {
        *p = *A;
        A++;
        p++;
    }

    for (int d = 0; d < b; d++) {
        *p = *B;
        B++;
        p++;
    }

    return original;
}

【讨论】:

  • 谢谢。我使用带有 O-- 的 for 循环将指针 O 返回到它的原始值。这行得通。
  • 请复制一份,递增一份,然后返回另一份——以后需要理解代码的人会更开心。
猜你喜欢
  • 2011-11-14
  • 1970-01-01
  • 2014-01-29
  • 2010-09-29
  • 2016-05-28
  • 2010-11-30
  • 2021-06-11
  • 2010-10-27
相关资源
最近更新 更多