0

I'm trying to make an array which have it's element coming from a user input. This array would first have it's size undefined since we don't know how much int would the user input, but then I'm not able to find the amount of element in the array like this unless I put a counter on the loop function. Here is the code that I've made:

int cross[] = {0};
  int k;
  for (k = 0; k >= 0; k++){
    scanf("%d", &cross[k]);
    if (cross[k] == -1){
      break;  //stop the user from inputing numbers if user input -1
  }
  int p = sizeof(cross) / sizeof(cross[0]);

If I were to do printf("%d", p), it would always give me 1 as a result. I'm wondering if there is any other way of doing this other than putting a counter on the for loop. Thanks!!

KittyCat
  • 35
  • 5
  • 2
    The array index `k` is also your counter. The calculation shows the length of the array, not how many elements were used. But `int cross[] = {0};` has only one element, so you need to rethink it. – Weather Vane Nov 18 '20 at 11:00
  • 2
    Also, arrays in C don't automatically grow in size. The `cross` array can store one element and that's it. Writing more elements to the array as you are doing will result in undefined behaviour. One option is to use dynamic allocation with `malloc` and grow with `realloc`. – kaylum Nov 18 '20 at 11:02
  • There is a solution posted here: [how to scanf unknown amount of integer numbers into array in C?](https://stackoverflow.com/questions/40972455/how-to-scanf-unknown-amount-of-integer-numbers-into-array-in-c) Although the accepted answer is for a 2D case, [another answer](https://stackoverflow.com/a/40973102/4142924) shows a simpler 1D case. You should get the idea from them for your own case, and there are many similar questions. – Weather Vane Nov 18 '20 at 11:05

1 Answers1

0

This phrase from your question is both wrong and dangerous: "This array would first have it's size undefined".

The following line of code defines a fixed-size array that has exactly one element:

int cross[] = {0};

The compiler knows it's one element because you supplied one initializer value {0}. If you supplied this {0, 5, 2}, it would allocate 3 integers, and so on.

This means when you store into cross[k] and k is larger than zero, you're actually exceeding the bounds of your allocated array, which C doesn't catch at compile time, but could cause nasty problems at run time.