Pointer to 2D arrays in C

后端 未结 4 2075
南笙
南笙 2020-11-28 04:01

I know there is several questions about that which gives good (and working) solutions, but none IMHO which says clearly what is the best way to achieve this. So, suppose we

4条回答
  •  一生所求
    2020-11-28 04:11

    Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

    int (*pointer)[280];
    pointer = tab1;
    

    pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

    When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

    In your second example, you explicitly create a pointer to a 2D array:

    int (*pointer)[100][280];
    pointer = &tab1;
    

    The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

    Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

    The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

提交回复
热议问题