1

I'm trying to initialize an integer array with variables that have scanned in values in C. The values in the array do not match what I scanned in. It stores weird numbers like -1040000000 or 37299 in the array instead.
Any help would be much appreciated, I'm pretty new to programming!

int num1;
int num2;
int num3;

int intarr[3] = {num1, num2, num3};

printf("Enter 3 numbers.\n");
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);

There are no error messages, but the numbers aren't what I inputted. For example, I scanned in numbers 1, 2, 3. And when I printed out the values at each index of my array, it printed out weird numbers like I stated above.

sine_nomine
  • 109
  • 1
  • 1
  • 7

1 Answers1

2

You're using num1, num2, and num3 to initialize the array before you fill in the variables with scanf(). You have to scan into the variables first, then assign them to the array.

int num1;
int num2;
int num3;

printf("Enter 3 numbers.\n");
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);

int intarr[3] = {num1, num2, num3};

You should enable full warnings from your compiler, it probably would have warned that you were using variables before initializing them. See Why should I always enable compiler warnings?

You could also skip the variables entirely, and just scan directly into the array.

printf("Enter 3 numbers.\n");
int intarr[3];
scanf("%d", &intarr[0]);
scanf("%d", &intarr[1]);
scanf("%d", &intarr[2]);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Or `if (scanf("%d%d%d", &intarr[0], &intarr[1], &intarr[2]) != 3) { …oops!… }`, using one call to read all three values, and checking that all three are read successfully. Using separate inputs, you should use something like: `if (scanf("%d", &intarr[0]) == 1 && scanf("%d", &intarr[1]) == 1 && scanf("%d", &intarr[2]) == 1) { …three values read OK… } else { …at least failed… }`. Or use a `for` loop to read one value at a time. – Jonathan Leffler Sep 17 '19 at 23:49
  • @JonathanLeffler Yeah, there are lots of ways to do it better, but this isn't [codereview.se]. So I kept it similar to the original code. – Barmar Sep 18 '19 at 15:20