Two dimensional arrays and pointers

后端 未结 4 1226
春和景丽
春和景丽 2021-01-18 04:23

I have the following code snippet:

char board[3][3] = {
                     {\'1\',\'2\',\'3\'},
                     {\'4\',\'5\',\'6\'},
                          


        
4条回答
  •  走了就别回头了
    2021-01-18 04:49

    It may be the case that you know an object-oriented language such as Java or Python, and now you are learning the C language. The difference between Java and C when thinking about char board[3][3] is that in C the board variable is represented in memory as 9 characters at adjacent memory addresses. Like so:

    board: 1 2 3 4 5 6 7 8 9
    

    In C, &board yields the same memory address as &board[0] and &board[0][0].

    In contrast to this, in Java the variable would be declared as char[][] board and its memory representation would conceptually look like this:

    board: ptr(A) ptr(B) ptr(C)
    A:     1 2 3
    B:     4 5 6
    C:     7 8 9
    

    where ptr(x) points to memory address of x. So, in Java, board points to a different memory address than board[0].


    You say In C, &board yields the same memory address as &board[0] and &board[0][0]. But i am able to access the first element only via board[0][0] (or) *board[0] (or) **board. Why is it so??

    Although the expressions &board and &board[0] and &board[0][0] yield the same address, the type system of the C language is preventing you from accessing the char value. In a C compiler, the types are (conceptually):

    board:       type char[3][3]
    board[0]:    type char[3]
    board[0][0]: type char
    

    Assuming a variable of type char, we can write:

    char c;
    c = board[0][0];
    

    but cannot write:

    char c;
    c = board;    // Error
    c = board[0]; // Error
    

    because the type on the left side is incompatible with the type on the right side of the assignment.

    If you are sure that an address points to a char, you can use a type cast:

    char c;
    c = *(char*)board;    // Works OK
    c = *(char*)board[0]; // Works OK
    

    The downside is that such type casts may lead to coding bugs.

提交回复
热议问题