简体   繁体   中英

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];

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.

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.

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM