dinesh
dinesh

Reputation: 805

Accessing an array of pointer to strings

Looking for some clarification on a specific topic related to addressing an array of strings. There seem to be several related issues but I wasn't able to find one that discussed my question. If this has been asked before please point me to the relevant thread.

In the snippet of code below (check printf statement), I use the same variable to access the value at a memory location and the address of the memory location. I'm not quite sure if this is how I'm supposed to write this piece of code. Is there a better way that will clearly indicate if I'm accessing the address or the value?

char *board[NUM_MAX_ROWS] = {"0101001",
                             "1101011"};

int main()
{
    int i, num_rows=0, num_cols=0;

    num_cols = strlen(board[0]);
    num_rows = ARR_SIZE(board);

    for (i=0; i<num_rows; i++)
        printf("%s stored at %p\n", board[i], board[i]);

} 

My first attempt looked like this

while(*board != '\0')
{
    printf("%s stored ar %p\n", *board, board);
    board++;
}

Obviously this doesn't work :) but I'm still not quite sure about how this is interpreted by the compiler.

Thanks.

Upvotes: 2

Views: 133

Answers (2)

shinkou
shinkou

Reputation: 5154

You could do it this way:

#include <stdio.h>

char *board[] = {"0101001",
                 "1101011",
                 0}; /* note this final 0 as a terminator for stopping the loop */

int main()
{
    int i, num_rows=0, num_cols=0;
    char **c;

    c = &board[0];
    while(*c)
    {
        printf("%s stored ar %p\n", *c, *c);
        c++;
    }

    return 0;
} 

However, you'll have to have a loop stopper if you do so. Also, there are people who advocate using NULL instead of 0 for clarity.

Upvotes: 0

Karthik T
Karthik T

Reputation: 31952

You can get the first attempt to work by dereferencing the pointer once to get address of the string itself.

printf("%s stored ar %p\n", *board, *board);

Btw when you write using array syntax, it is actually identical to

printf("%s stored ar %p\n", *(board+i), *(board+i));

Edit: i seem to have miss read the question.. fixing.

Upvotes: 1

Related Questions