Matias Rodriguez
Matias Rodriguez

Reputation: 81

"Array subscript is not an integer" in C program

The deviation function throws me the following error: "Array subscript is not an integer". If you can help me locate the cause of error I'll appreciate it.

float average(float data[], int n) {
    float total = 0;
    float *p = data;

    while (p < (data + n)) {
        total = total + *p;
        p++;
    }

    return total / n;
}

float deviation(float data[], int n) {
    float data_average = average(data, n);
    float total;
    float *p = data;

    while (p < (data + n)) {
        total += (data[p] - data_average) * (data[p + 1] - data_average);
    }

    return total / 2;
}

Upvotes: 7

Views: 107923

Answers (4)

chux
chux

Reputation: 154085

C11dr 6.5.2.1 Array subscripting ... "One of the expressions shall have type ‘‘pointer to complete object type’’, the other expression shall have integer type, and the result has type ‘‘type’’." ...

With [], you get to do:

// pointer_type[integer_type]
float data[];
int n;
float total;
total = data[n];

// or the unconventional equivalent
// integer_type[pointer_type]
total = n[data];  // But let's leave that for another post

// Instead the OP did
// pointer_type[pointer_type]
// and received error: "Array subscript is not an integer"
float *p;
total = data[p];

The usage of float is not the issue here, but the usage of a pointer.

An integer type includes types int, unsigned, size_t, long, etc.


I think the OP wanted the following (or something like this)

float deviation(float data[], int n) {
  if (i <= 0) return 0;
  float data_average = average(data, n);
  float total = 0.0;  // don't forget to set to 0.0
  float *p = data;

  while (p < (data + n)) {
    total += (*p - data_average) * (*p - data_average);
    p++;
    }
  return sqrt(total / n);  // div by 0 averted
}

Upvotes: 2

Mr Lister
Mr Lister

Reputation: 46589

You can use an int:

int p = 0;
...
while (p<n) {
    // rest is the same

or, you can use p as a pointer directly, which is, I suppose, what you intended.

while(p<datos+n) {
    total += (*p-prom)*(*(p+1)-prom);

Note, however, that you never increment p, so the loop will never end. Also, you never initialise total, so the result will be a random garbage value.

Upvotes: 2

haccks
haccks

Reputation: 106092

Array subscripts must be an integer, an int type. You can't use any other type as array subscript. p is declared as float *p, i.e, a pointer to float. You can't use a pointer as array indices.

Upvotes: 3

sandymatt
sandymatt

Reputation: 5612

p is a pointer to a float. That's why you're getting the error.

float *p, total;

...

total += (datos[p]-prom)*(datos[p+1]-prom);

You can only use ints as array indices in C.

Upvotes: 8

Related Questions