My friend made a program in C that gets 2 inputs. One being the length of the array and the other being the elements of the array. The code works fine, except for when the length of the array is 5. When the length of the array if 5, the first element becomes the same as the last element in the array (e.g. if the elements were 1, 2, 3, 4, 5, then it would be switched to 5, 2, 3, 4, 5). Here is the code he wrote:
#include <stdio.h>
int main()
{
int length;
printf("What is the length of your array?: ");
scanf("%d", &length);
length -= 1;
int X[length], Y[length];
printf("What are the elements of your array?: \n");
for (int i = 0; i <= length; i++)
{
scanf("%d", &X[i]);
Y[i] = X[i];
}
printf("\n");
for (int i = 0; i <= length; i++)
{
printf("%d ", X[i]);
}
printf("\n");
for (int i = length; i >= 0; i--)
{
printf("%d ", Y[i]);
}
}
I tried searching the internet, but no matter what I do, I can't really wrap my head around what's happening.
Edited: Indeed, reserve memory for 5, then use 1 less to iterate, as comments mention! You want 5, so it will go from 0 to 4. (1,2,3,4,5). -
So this:
scanf("%d", &length);
length -= 1;
int X[length], Y[length];
Should change to
scanf("%d", &length);
int X[length], Y[length];
length -= 1;
Or do not decrease length and in the for loop, use
for (int i = 0; i < length; i++)
Playing before with my previous answer, using malloc makes this work, BUT, having the right output does not necessarily mean it is correct:
scanf("%d", &length);
length -=1;
//int X[length], Y[length];
int *X, *Y;
X,Y = (int *) malloc(length);
After that, with 5:
What is the length of your array?: 5
What are the elements of your array?:
1
2
3
4
5
1 2 3 4 5
5 4 3 2 1