-2

I have this piece of code:

#include <stdio.h>

int average(int array []);

int main () {

int num_array[];


int x = 0;

  while(num_array[x] != -1){

     printf("Enter a number\n");
     scanf("%d",&num_array[x]);

     x++;

  }

  printf("%d\n", average(num_array));

  return 0;
}



int average(int array[]){

  int i;
  int total_size = (int)sizeof(array);
  int sum = 0;

  for(i = 0; i < total_size; i++){

    sum = sum + array[i];

  }

  return sum/total_size;

}

But i get an error at compile time, because i'm not initialising the array. However i can't do it, since i don't know it's size.

How can i solve this ?

laker001
  • 417
  • 7
  • 20

3 Answers3

1

You can't declare an array like

int num_array[];  

in C except when it is a parameter of a function. You must have to specify the size.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

This is actually a surprisingly tricky problem in C unless you're using an array library. What you're actually talking about is a growable array. For what you're trying to do, you start with an initial size, say 10, using malloc() and as the inputs grow, you have to realloc() the array to a larger size. Generally, you double the size of the array every time the limit is hit. If you're a beginning C programmer, this is probably too much to take on. I would set a fixed limit, and enforce it by not accepting any more input after the limit is hit. Given that you can comfortably allocate 1000's of ints and a human won't want to type that much, you can easily make a practical limit ahead of time and declare the array as such:

int num_array[1000];
BaseZen
  • 8,650
  • 3
  • 35
  • 47
0

You need to provide the size of the array here: int num_array[];.

If you are working with a structure of unknown size, you could:

  • Ask the user how many numbers are going to be entered (not really practical, but might suffice if your case is a trivial one).

  • Initialize it with a default size, say 10 and then if you need, create larger arrays and copying your current data to the new one.

  • Or else, you use a linked list like data structure and create new elements as you go along, thus allowing your list to grow as much as you need it to be.

npinti
  • 51,780
  • 5
  • 72
  • 96