【发布时间】: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 0和return O在这段代码中的含义很不一样... -
return O;:O与 malloc 的返回不同,因为O++; -
一个问题是你没有抓住 malloc 的返回值,所以释放它会很困难
-
啊^ 谢谢。我忘了我做了O ++。 @MichaelAnderson,我知道我不应该使用 O,这很混乱,会改变它。
-
@JCodder
int NewArray[c]这不是有效的 C++(您已将问题标记为 C++)。如果是C++,那么std::vector<int>的使用将/可以/应该代替malloc。