C, passing 2 dimensional array

前端 未结 2 469
清歌不尽
清歌不尽 2020-12-12 03:37

I haven\'t used pure C in a few years now, but I can\'t seem to make this really basic use case work. Here is the simple use-case in simple C, the actual situation is wrapp

相关标签:
2条回答
  • 2020-12-12 03:56
    void print_data(float **data, int I, int J)
    

    expects an array of pointers to (the first element of arrays of) float.

    But when you pass

    float data[4][6];
    

    you pass a pointer to float[6].

    So in print_data, an access to

    data[i]
    

    reads sizeof(float*) bytes at an offset of i * sizeof(float*) bytes after what address data holds, and interprets these bytes as a float* that it then dereferences (after adding a suitable offset) in data[i][j].

    So when you pass your 2D array, some float values are interpreted as pointers and then followed. That often leads to a segmentation fault.

    You can either declare

    void print_data(float (*data)[6], int I, int J)
    

    and pass your 2D array, or you need to pass an array of pointers,

    float *rows[4];
    for(i = 0; i < 4; ++i) {
        rows[i] = &data[i][0];
    }
    

    and pass rows. Or, the third possibility is to pass and expect a flat array

    void initialize_data(float* data, int I, int J) {
        for(i = 0; i < I; ++i) {
            for(j = 0; j < J; ++j) {
                data[i*J + j] = whatever;
            }
        }
    }
    

    and pass &data[0][0] from main.

    0 讨论(0)
  • 2020-12-12 04:05

    A bi-dimensionnal array is not evaluated as a pointer to pointer, so you need to use an array of a pointer to array in your prototype:

    void print_data(float data[4][6]);
    void print_data(float (*data)[6]);
    
    0 讨论(0)
提交回复
热议问题