array as parameter of a function

后端 未结 3 802
旧巷少年郎
旧巷少年郎 2021-01-24 05:09

There is a array of structures.

    static field fields[xsize][ysize];

I want to change it in function

    void MoveLeft(pacma         


        
相关标签:
3条回答
  • 2021-01-24 05:34

    Although arrays and pointers are somewhat interchangeable in C, they're not exactly the same. In particular, an array of arrays and an array of pointers are laid out differently in memory.

    Here's a way to make an array of pointers which refers to the same data as your existing array of arrays:

    field* field_rows[xsize];
    for (unsigned int i=0; i<xsize; i++) {
        field_rows[i] = fields[i];
    }
    

    Then a pointer to that field_rows array can be passed to MoveLeft:

    MoveLeft(&Pacman,field_rows,play);
    

    Another solution might be to change the declaration of MoveLeft instead, to take a pointer to array of arrays:

    void MoveLeft(pacman *Pacman, field fields[xsize][ysize], int **play);
    
    MoveLeft(&Pacman,fields,play);
    
    0 讨论(0)
  • 2021-01-24 05:34

    I guess the error is the following: two dimension array fields[xsize][ysize] is fixed size array (xsize/ysize are defines or consts) and in memory this is not look like field**, cause it's pointer to pointer to field, while fields[xsize][ysize] internally just one dimension fixed size array, where compiler handle double indexing for you.

    So what you need is just define fields as field** and allocate it dynamically.

    See picture for more explanation: enter image description here

    0 讨论(0)
  • 2021-01-24 06:00

    While I'm not using Windows, I'm guessing your error is something similar to this:

    error: cannot convert ‘field (*)[xx]’ to ‘field**’ for argument ‘2’ to ‘void MoveLeft(pacman*, field**,int**)’
    

    A solution to this is to simply cast the fields parameter to the type the function wants:

    MoveLeft(&Pacman, (field **) fields, play);
    
    0 讨论(0)
提交回复
热议问题