user1637319
user1637319

Reputation: 13

C Warning: assignment makes integer from pointer without a cast

I'm having trouble figuring out why my program is giving me this error. The function is suppose to sum up all the numbers in the array, then find the average. Right now, I'm having problems summing up the elements.

float Average(int **array, int n) {
  int sum = 0;
  int i;
  for (i = 0; i < n; i++){
    sum = sum + array[i];
  }
  return sum/n;
}

The parameter array is dynamically allocated in the main method and n is the size of the array.

The error is coming from this line, but I don't know why.

sum = sum + array[i];

Upvotes: 0

Views: 6031

Answers (4)

Chimera
Chimera

Reputation: 6018

You probably want this:

float Average(int *array, int n) {
  int sum = 0;
  int i;
  for (i = 0; i < n; i++){
    sum = sum + array[i];
  }
  return sum/n;
}

You only need **array if for some reason you wanted to change where *array points.

Upvotes: 5

Alec Danyshchuk
Alec Danyshchuk

Reputation: 307

Ben is correct. If your array is a simple list, this is an example solution,

main(int argc, char * argv[])
{
int ia[10] = {3,2,3,4,5,6,7};
float ans = 0;

  ans = Average(ia,7);
  printf("Ans %f\n",ans);
  exit(0);
}

float Average(int *array, int n)
{
int sum = 0;
int i;

  for (i = 0; i < n; i++){
    sum = sum + array[i];
  }
  printf("Calc %d / %d\n",sum,n);
  return (float)sum/n;
}

Upvotes: 1

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14565

Your array is actually an array of arrays (**), so you are calculating the average value of the starting virtual memory address of each array in your array.

The compiler is just trying to tell you that, which in most cases is not the programmer's desired result. The conversion could also fail if the pointer value is larger than a 32 bit integer.

A cast would tell the compiler I'm sure about what I'm doing:

(int)array[i]

But I don't think that is what you want, right?

Upvotes: 2

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

The reason this is happening is because array is a double pointer. ie. deferencing the array:

*array

gives you this:

int *array

Which is still a pointer.

Consider whether you need the double pointer and if not you will need to deference it twice:

array[1][2]

Hope this helps.

Upvotes: 3

Related Questions