Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C subscripted value is neither array nor pointer nor vector when assigning an array element value

Tags:

Sorry for asking the already answered question, I am a newbie to C and don't understand the solutions. Here is my function

int rotateArr(int *arr) {     int D[4][4];     int i = 0, n =0;     for(i; i < M; i ++ ){         for(n; n < N; n++){             D[i][n] = arr[n][M - i + 1];         }     }     return D; } 

It throws an error

main.c|23|error: subscripted value is neither array nor pointer nor vector|

on line

D[i][n] = arr[n][M - i + 1];

What's wrong? I am just setting the value of an array element to another array element.

The arr passed is declared as

int S[4][4] = { { 1, 4, 10, 3 }, { 0, 6, 3, 8 }, { 7, 10 ,8, 5 },  { 9, 5, 11, 2}  }; 
like image 654
Euphe Avatar asked Nov 11 '13 14:11

Euphe


1 Answers

C lets you use the subscript operator [] on arrays and on pointers. When you use this operator on a pointer, the resultant type is the type to which the pointer points to. For example, if you apply [] to int*, the result would be an int.

That is precisely what's going on: you are passing int*, which corresponds to a vector of integers. Using subscript on it once makes it int, so you cannot apply the second subscript to it.

It appears from your code that arr should be a 2-D array. If it is implemented as a "jagged" array (i.e. an array of pointers) then the parameter type should be int **.

Moreover, it appears that you are trying to return a local array. In order to do that legally, you need to allocate the array dynamically, and return a pointer. However, a better approach would be declaring a special struct for your 4x4 matrix, and using it to wrap your fixed-size array, like this:

// This type wraps your 4x4 matrix typedef struct {     int arr[4][4]; } FourByFour; // Now rotate(m) can use FourByFour as a type FourByFour rotate(FourByFour m) {     FourByFour D;     for(int i = 0; i < 4; i ++ ){         for(int n = 0; n < 4; n++){             D.arr[i][n] = m.arr[n][3 - i];         }     }     return D; } // Here is a demo of your rotate(m) in action: int main(void) {     FourByFour S = {.arr = {         { 1, 4, 10, 3 },         { 0, 6, 3, 8 },         { 7, 10 ,8, 5 },         { 9, 5, 11, 2}     } };     FourByFour r = rotate(S);     for(int i=0; i < 4; i ++ ){         for(int n=0; n < 4; n++){             printf("%d ", r.arr[i][n]);         }         printf("\n");     }     return 0; } 

This prints the following:

3 8 5 2  10 3 8 11  4 6 10 5  1 0 7 9  
like image 125
Sergey Kalinichenko Avatar answered Sep 21 '22 06:09

Sergey Kalinichenko