Outputting huge number when using an array to print out even and odd numbers on C

Viewed 45

I was asked to code a program that asks for an integer 'n', then scan for 'n' integers, and then sort and print those integers in even numbers, ascending, then the odd numbers, descending.

So I began by having the even numbers in the first column of an array, and then the odd numbers in the second column, and then print them, but at the end I'm getting nothing but huge, similar numbers instead of the values I initially entered.

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

int main()
{
  int array1_size, unfill;
  printf("How many integers do you wish to enter?\n");
  scanf("%d",&array1_size);
  int array1[array1_size][2];

  for (int i = 0; i < array1_size; ++i)
  {
    printf("Enter integer number %d\n", i+1);
    scanf("%d",&array1[i][0]);
  }

  for (int i = 0; i < array1_size; ++i)
  {
   if ( (array1[i][0] % 2) != 0 )
    {
      array1[i][1] = array1[i][0];
      array1[i][0] = unfill;
    }
  }

  printf("Your even numbers are:\n");
  for (int i = 0; i < array1_size; ++i)
  {
    printf("%d\n", array1[array1_size][0]);
  }

  printf("...and your odd numbers are:\n");
  for (int i = 0; i < array1_size; ++i)
  {
    printf("%d\n", array1[array1_size][1]);
  }

  return(0);
}
1 Answers

You declare

int array1[array1_size][2];

The highest-index legally accessable element inside that is

array1[array1_size-1][2-1]

This line is hence highly suspicious

printf("%d\n", array1[array1_size][1]);

Also you do not initialise unfill but copy its content elsewhere here

array1[i][0] = unfill

You possible leave the content of any array1[i][0] non initialised, because your code is vulnerable by a failing scanf(), because here you ignore the usually very helpful return value, which could warn you in case anything went wrong with scanning.

scanf("%d",&array1[i][0])

Any of these issues could be the explanation of your observed huge numbers, which sometimes are a symptom of using non-initialized variables or content of illegally accessed memory.

Related