简体   繁体   中英

What does this array error mean?

void arrayRound(int id, double baln)
{
    baln[id] = (baln[id]*100) + 0.5;
    int temp = (int) baln[id];
    baln[id] = (double) temp;
    baln[id] = baln[id] / 100;
}

The function body is what is giving me error messages. The function is meant to round an array index to the nearest hundredth. I separately passed both the index variable and the array to the function. Here is the error message:

Fxns.c:70: error: subscripted value is neither array nor pointer
Fxns.c:70: error: subscripted value is neither array nor pointer
Fxns.c:71: error: subscripted value is neither array nor pointer
Fxns.c:72: error: subscripted value is neither array nor pointer
Fxns.c:73: error: subscripted value is neither array nor pointer
Fxns.c:73: error: subscripted value is neither array nor pointer

My first guess was that I needed to include empty brackets after the baln in the parameter field, but that didn't help. Any ideas?

您正在尝试治疗baln类型的double像一个数组(使用索引)。这是行不通的。

Your parameter should be declared as

double *baln

a pointer to double , or as double baln[] , which reads like an array of double s, but as a function parameter also denotes a pointer.

void arrayRound(int id, double *baln)
{
    baln[id] = (baln[id]*100) + 0.5;
    int temp = (int) baln[id];
    baln[id] = (double) temp;
    baln[id] = baln[id] / 100;
}

will compile, but since you don't know what size the memory block baln points to is, you may access unallocated memory in this function, if you are not careful.

You had it right; you do need to include empty brackets after baln in the parameter list, like so:

void arrayRound(int id, double baln[]);

Here's a full demo.

error: subscripted value is neither array nor pointer

baln[id]

Subscripted Value = baln

Operator [] , can only be used either on arrays or pointers. In your case, baln is neither. It is of type double but not double[] or double* .

int a[] = { 1,2,3,4,5 };
a[0] = 10;  // Notice the use of `[]`.This is valid because `a` is an array type.

int b = 10;
int * ptr = &b;
ptr[0] = 99;   // Valid because ptr is a pointer type but cause undefined
               // behaviour for any other index in this example.

*ptr = 99 ; // This is more readable than the earlier case.

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