Before anybody flags this as Duplicate, it is not.
So I have this array
int arr[6];
I want to split it into two different arrays based on the indexes. Now this is my program :
#include <stdio.h>
int main()
{
int arr[6], a[3], b[3], i, j, n, aa = 0, bb = 0;
printf("How many elements ? \n");
scanf("%d", &n);
printf("Enter the numbers : \n");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
for (i = 0; i < n; i++)
{
if (i == 0 || i % 2 == 0)
{
// even
a[i] = arr[i];
aa++;
// For debug purpose
printf("a[%d]=%d, arr[%d]=%d, aa=%d\n", i, a[i], i, arr[i], aa);
}
else
{
// odd
b[i] = arr[i];
bb++;
// For debug purpose
printf("b[%d]=%d, arr[%d]=%d, bb=%d\n", i, b[i], i, arr[i], bb);
}
}
// For debug purpose
printf("aa=%d bb=%d n=%d\n", aa, bb, n);
printf("THE NUMBERS are :\n");
for (i = 0; i < aa; i++)
printf("%d ", a[i]);
printf("\n");
for (i = 0; i < bb; i++)
printf("%d ", b[i]);
printf("\n");
}
The problem is, I am getting garbage values as output. This does not even make any sense when the debug logs show everything is alright.
user@HOME-PC:~$ gcc test.c && ./a.out
How many elements ?
6
Enter the numbers :
2 3 4 5 6 7
a[0]=2, arr[0]=2, aa=1
b[1]=3, arr[1]=3, bb=1
a[2]=4, arr[2]=4, aa=2
b[3]=5, arr[3]=5, bb=2
a[4]=6, arr[4]=6, aa=3
b[5]=7, arr[5]=7, bb=3
aa=3 bb=3 n=6
THE NUMBERS are :
2 32616 4
32616 6 0
I have tried giving the program input directly before run time but that too doesn't work.
int arr[6] = {2, 3, 4, 5, 6, 7};
int a[3], b[3];
int aa = 0, bb = 0, n = 6;
int i, j;
I want to know, whether my program has a problem, or the compiler has some issues. I shall also try this with clang compiler.
Also the code is available on repl.it for anyone to run and check. https://repl.it/@Kogam22/CArrayIndexOddEven
Running on clang gives garbage values too.
clang version 7.0.0-3~ubuntu0.18.04.1 (tags/RELEASE_700/final)
clang-7 -pthread -lm -o main main.c
./main
How many elements ?
6
Enter the numbers :
2 3 4 5 6 7
a[0]=2, arr[0]=2, aa=1
b[1]=3, arr[1]=3, bb=1
a[2]=4, arr[2]=4, aa=2
b[3]=5, arr[3]=5, bb=2
a[4]=6, arr[4]=6, aa=3
b[5]=7, arr[5]=7, bb=3
aa=3 bb=3 n=6
THE NUMBERS are :
5 0 7
4196381 3 1771501984
At this point, I am thinking I screwed up somewhere. Any help would be appreciated.
Any access to a[i]
or b[i]
will be out of bounds when i
is greater than 2. You should be using the aa
and bb
indices when filling the a[]
and b[]
arrays.
Also, the test for even or odd indices can be simplified since 0 is even.
Here is the fixed version of the array splitting loop:
for (i = 0; i < n; i++)
{
if (i % 2 == 0)
{
// even
a[aa] = arr[i];
// For debug purpose
printf("a[%d]=%d, arr[%d]=%d, aa=%d\n", aa, a[aa], i, arr[i], aa);
aa++;
}
else
{
// odd
b[bb] = arr[i];
// For debug purpose
printf("b[%d]=%d, arr[%d]=%d, bb=%d\n", bb, b[bb], i, arr[i], bb);
bb++;
}
}