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

后端 未结 6 767
悲&欢浪女
悲&欢浪女 2020-12-09 09:36

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         


        
6条回答
  •  伪装坚强ぢ
    2020-12-09 10:20

    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 
    

提交回复
热议问题