Reputation: 99
I've been trying to make a function that appends matrix B onto Matrix A by making a new combined matrix. The first function I created passes a pointer (that was declared in main()) to the function which then works up the pointer to add values. This worked. However, I am also trying a different method by using malloc() within the function to define a pointer so that the function is more portable and dyanmic. However, when I try to print the final values in the final matrix I am getting undefined behavior.
Here is the included function from the created header file.
#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;
}
Here is the use of the function in 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;
}
Upvotes: 0
Views: 92
Reputation: 73600
Your problem is that you increment O and then return it.
You need to save away the original value and increment a copy.
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;
}
Upvotes: 2