erengsgs erengsgs - 1 month ago 5
C Question

adding two arrays in C

The problem is basically printing two arrays on an external array as right part and left part but although I can print one part, I can not print the other part. The scenario is that for example 5 elements on the left and 7 at the right. Then it reverses the right side and sticks it to the beginning of the array.

Here is the piece of code that I typed.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int mainarray[] = {} , n , i , rank;

printf("\nHow many element[10..2000]: ");
scanf("%d", &n);
printf("\nEnter the array elements : ");
for(i=0; i<n; ++i)
{
scanf("%d" , &mainarray[i]);
}
printf("\nThe array is : ");
for(i=0 ; i<n ; i++)
{
printf("%d ",mainarray[i]);
}
printf("\n\nEnter the rank of the element : ");
scanf("%d",&rank);
printf("\n\nElement on rank %d is: %d",rank, mainarray[rank-1]);


int leftarray[] = {} , rightarray[] = {};

for(i=0; i<=rank ; i++)
{
leftarray[i] = mainarray[i];
}
printf("\n\nThe left array is : ");
for(i=0 ; i<=rank ; i++)
{
printf("%d ", leftarray[i]);
}

for(i=0 ; i<n-rank-1 ;i++)
{
rightarray[i]=mainarray[i+rank+1];
}
printf("\n\nThe right array is : ");
for(i=0 ; i<n-rank-1 ;i++)
{
printf("%d ", rightarray[i]);
}

int j=n-rank-2,temp;
i=0;
while(i<j)
{
temp=rightarray[i];
rightarray[i]=rightarray[j];
rightarray[j]=temp;
i++;
j--;
}
printf("\n\nNew right array is : ");
for(i=0 ; i<n-rank-1 ; i++)
{
printf("%d ", rightarray[i]);
}

i=0;

while(i<n-rank-1)
{
mainarray[i]=rightarray[i];
i++;
}
j=0;
while(j<rank+1 && i<n-1)
{
mainarray[i]=leftarray[j];
j++;
i++;
}

printf("\n\nThe result is : ");
for(i=0 ; i<n ; i++)
{
printf("%d ",mainarray[i]);
}

printf("\n\n\n");
system("pause");
return 0;
}

Answer

You're declaring empty arrays when you write:

int mainarray[] = {};

As a result, you're storing outside the array bounds, which results in undefined behavior.

You need to declare the arrays after you get the size from the user.

scanf("%d", &n);
int mainarray[n]; // no need to initialize here, you're going to fill it in with the input loop

Then do similar things for leftarray and rightarray:

scanf("%d",&rank);
int leftarray[rank];
int rightarray[n-rank];
Comments