0

So I have created a function that takes as input two arrays and its lengths, and puts the elements of the two arrays into a new one which alternates the elements and then returns the new array. Here is the code:

int* alt(int a1[], int n1, int a2[], int n2)
{
int n = n1 + n2, i, index=0;
int A[n];
if (n1>n2)
    for (i=0; i<n; i++)
    {
        if (i%2==0 || index>=n2)
            A[i] = a1[index];
        else if (index<n2)
            A[i] = a2[index];
        index++;
    }
else
    for (i=0; i<n; i++)
    {
        if (i%2==1 || index>=n1)
         {
            A[i] = a2[index];
            index++;
         }
        else if (index<n1)
            A[i] = a1[index];
    }
return A;
}

This is how I call the function in main:

A=alt(A1, n1, A2, n2);

where A is declared of type int*

Then I proceed to print the arrays. However I get garbage values when printing A. By debugging, the functions seems to work fine and return the right address. Any ideas what might be the problem?

Thanks in advance.

EDIT: I don't get it though why in this example it is working fine?

user3484582
  • 557
  • 1
  • 6
  • 22
  • Can anybody explaing why it is working fine [in this example](http://www.tutorialspoint.com/cprogramming/c_return_arrays_from_function.htm)? – user3484582 Apr 06 '15 at 17:26
  • It works in that example because the array (pointer) being returned is declared `static`, meaning that its existence persists after the termination of the function call. In your case, your array ceases to exist when you `return` from the function. You probably won't be able to use `static` in your case, though, since the size of your desired array is not fixed. You'll want `malloc()` and `free()` instead... – twalberg Apr 06 '15 at 18:17
  • @twalberg oh makes sense! Didn't know about static. Yeah, I immediately fixed with malloc( and it works fine. Thanks for the clarification. – user3484582 Apr 06 '15 at 19:05

0 Answers0