Jakub
Jakub

Reputation: 699

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];

Upvotes: 1

Views: 62

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84561

You can round out you question with a short exercise putting the pointer assignments to use. For example continuing from the comment above, with the creation of myptr as a pointer-to-aray of char[20] and s and t to an array of char[20], you could do:

#include <stdio.h>

int main (void) {

    const char name[20][20] = { "Mickey Mouse", "Minnie Mouse", "Pluto",
                                "Bugs Bunny", "Porky Pig", "Daffy Duck", "" },
                (*myptr)[20] = name;

    while (1) {
        const char *s = *myptr++, *t = *myptr++;

        if (*s)
            puts (s);
        else
            break;

        if (*t)
            puts (t);
        else
            break;
    }
}

Example Use/Output

$ ./bin/ptr2arrexercise
Mickey Mouse
Minnie Mouse
Pluto
Bugs Bunny
Porky Pig
Daffy Duck

Question: What purpose does the empty-string serve as the last element of name in the code above?

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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];

Upvotes: 2

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

Here's how you declare a pointer to an array of 20 elements:

char (*ptr)[20];

So, this is how you do what you want to do:

char name[20][20];
char (*s)[20] = &name[1]; // note the &
char (*t)[20] = &name[2];

And here's how you access elements of those arrays later on:

for (size_t i = 0; i < sizeof(*s); ++i) {
  printf("%d ", (*s)[i]);
}

Upvotes: 1

Related Questions