Scerzyy
Scerzyy

Reputation: 52

Variables in C unexpectedly change

I'm writing a code to split an array into 2 different ones, one with even numbers and one with odd numbers. I read the numbers from a file, put it all into an array, and get the split right. Here's the code where everything works:

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

int main(int argc, char** argv){
  FILE* fpointer;
  if (argc >= 2){
    fpointer = fopen(argv[1], "r");
  }else{
    printf("No filename or multiple file names given");
    return 0;
  }
  int numElem;
  fscanf (fpointer, "%d\n", &numElem);
  printf("Number of elements is %d\n", numElem);
  int* arr;
  int numEvens;
  int numOdds;
  arr = (int*) malloc(numElem*sizeof(int));
  for (int i = 0; i < numElem; i++){
    int temp;
    fscanf(fpointer, "%d", &temp);
    if(temp%2 == 0){
       numEvens++;
    }else{
      numOdds++;
    }
    arr[i] = temp;
  }
  fclose(fpointer);

printf("number of evens: %d \n number of odds: %d\n", numEvens, numOdds);
  //The array is now in "arr"
   int* evens;
   int* odds;
   evens = (int*) malloc(numEvens*sizeof(int));
   odds = (int*) malloc(numOdds*sizeof(int));
  int a = 0;
  int b = 0;
  for (int i=0; i < numElem; i++){
    printf("%d\n", arr[i]);
    if (arr[i]%2 == 0){
      evens[a] = arr[i];
      a++;
    }else{
      odds[b] = arr[i];
      b++;
    }
  }
  printf("EVENS: %d\n", numEvens);
  for (int i=0; i < numEvens; i++){
    printf("%d\n", evens[i]);
  }
  printf("ODDS: %d\n", numOdds);
  for (int i=0; i < numOdds; i++){
    printf("%d\n", odds[i]);
  }

Now I have a neat array with even numbers, and one with odd numbers. It outputs numEvens and numOdds correctly. Then I attempt to sort it:

  int temp;
  int x;
  int y;

  for (x = 0; x < numEvens-1; x++){
    for (y=x+1; y < numEvens; y++){
      if (evens[y] < evens[x]){
    temp = evens[y];
    evens[y] = evens[x];
    evens[x] = temp;
      }
    }
  }

  return 0;

}

The output before I add in the sort method is:

Number of elements is 8
number of evens: 5 
 number of odds: 3
25
10
1
99
4
2
8
10
EVENS: 5
10
4
2
8
10
ODDS: 3
25
1
7

And the new output becomes:

Number of elements is 8
number of evens: 32772 
 number of odds: 1764530596
25
10
1
99
4
2
8
10
EVENS: 32772
10
4
2
8
10
0
0
0
0
....

The 0's go on presumably for another 32,000 times until I abort. I'm trying my hand at C after coming from java so memory allocation is a new subject for me, but I'm assuming it has something to do with that. I just don't understand how variables can be changed by lines of code added in after they are declared and printed. I don't really need help with new sorting methods, I just want some pointers on what's happening here so I can fix the errors. Thanks in advance!

Upvotes: 0

Views: 56

Answers (1)

Swordfish
Swordfish

Reputation: 13134

int numEvens;
int numOdds;

Initialize your variables:

int numEvens = 0;
int numOdds = 0;

... and don't cast the result of malloc()!

Upvotes: 2

Related Questions