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?