简体   繁体   中英

Error on subscripted value is neither array nor pointer nor vector

I read other answer too related to this error but my question is not that how to solve it. Rather it is why there is the difference in below two snippets

void sortArray(int a[],int n,int x){
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      int a = abs(x-a[j]);
      int b = abs(x-a[j+1]);
      if(a > b)
        swap(&a[j],&a[j+1]);
   }
  }
}

The other snippets does generates the error.

void sortArray(int a[],int n,int x){
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      if(abs(x-a[j]) > abs(x-a[j+1]))
        swap(&a[j],&a[j+1]);
   }
  }
}

While the above one does not. I wanted to know the internal working.

Error is on line no: 4,5 and 7 in first code: Subscripted value is neither array nor pointer nor vector

The crux of the matter is the variable names. Allow me to remove everything that is irrelevant from the first function:

void function(int a[]){
      int a = /* whatever */;
      a[0];
}

You have two things referred to by the same identifier ( a ). In both C and C++ the rules dictate that a later declaration will hide the previous declaration. So the integer hides the pointer from the moment it is declared (recall that "arrays" are adjusted to pointers in function parameter lists), and you lose the ability to refer to the pointer parameter.

That's why a[i] is an invalid expression, because the a it attempts to subscript is no longer an array or pointer.

The error is here:

 int a = abs(x-a[j]);

Prior to this line, a is defined with type int [] . But at this line, you redefine a as an int which masks the prior definition. As a result the expression a[j] is referring to the newly declared a which is not a pointer or an array.

Change the name of this variable to something else:

  int c = abs(x-a[j]);
  int b = abs(x-a[j+1]);
  if(c > b)
    swap(&a[j],&a[j+1]);

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