Search code examples
carrayspointersimplicit-conversion

How to use several pointers to one twodimensional array in c?


I want to create pointers on array in c. For example, I have an array

char arr1[4][20];

I want to make pointers and these pointers would get memory like this pointer p = arr1[0][0-20] t = arr1[1][0-20], u = arr[1][0-20]. I want to keep all strings from different files in one array. I try to do something like that, but it's not working.

char name[20][20];
char *s[20];
char *t[20];
s = name[1];
t = name[2];

Solution

  • An array declared like this

    char name[20][20];
    

    used in expressions as for example an initializer is implicitly converted to pointer to its firs element that is has the type char ( * )[20].

    So you may write for example

    char ( *s )[20] = name;
    

    In this case for example to traverse character elements of the array pointed to by the pointer s you need to use expressions like

    ( *s )[0], ( *s )[1], an so on
    

    Or like

    s[0][0], s[0][1], and so on.
    

    It will be simpler to traverse pointed character arrays if pointer would be declared like

    char *s = name[0];
    char *t = name[1];
    

    and so on.

    So either you should declare pointers like

    char ( *s )[20] = name;
    char ( *t )[20] = name + 1;
    

    or like

    char *s = name[0];
    char *t = name[1];