Accessing an array of one-dimensional pointers with two dimensions

I have the following question about homework:

Consider the following declarations and answer the question.
char strarr1[10][32];
char *strarr2[10];

Are strarr1[3][4] and strarr2[3][4] both legal references?

I tried compiling code with gcc to check it out. I was sure that the second link would throw an error, but it is not. This is what I compiled with gcc:

int main(void){
    char strarr1[10][32];
    char *strarr2[10];

    char x = strarr1[3][4];
    char y = strarr2[3][4];

    return 0;
}

I work on the assumption that the test code used is correct.

How can one refer to strarr2 [3] [4] when strarr2 is a one-dimensional array?

+3
source share
3 answers

since it strarr2is an array of char *, the second [4]is an index in char *

it means the same as this

char * temp = strarr2[3];
char y = temp[4];

, strarr2, , strarr2 [3] , . , segfault.

+1

- . :

char y = strarr2[3][4];  // <--- NOT SAFE!

undefined, .

, .

+1

This is a one-dimensional array of pointers. So, you are indexing the pointer to 3 with an offset = 4:

char y = *(strarr2[3] + 4);

matches with:

char y = strarr2[3][4];
0
source

Source: https://habr.com/ru/post/1731961/


All Articles