Hi there, I am not able to visualize what this code exactly creates in the memory, though I can understand that this is array of pointers:

char *dic[][40] = {
"atlas", "A volume of maps.",
"car", "A motorized vehicle.",
"telephone", "A communication device.",
"airplane", "A flying machine.",
"", "" /* null terminate the list */
};

Visual Studio Debugger View for degging inside the dic variable
[IMG]http://img37.imageshack.us/img37/1047/arrtoptr.png[/IMG]

Please help me to understand what this statement is creating, element by element as they are nested (or say referenced).

Recommended Answers

All 3 Replies

Not 100% sure how to explain how it holds all the memory but I think this is what you are aiming for.

When I compiled your code I was getting warning and it crashed on run-time.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *dic[][40] = { {"Atlas", "A volume of maps"}, {"Car", "A motorized vehicle"} };

	int i;
    for( i = 0; i < 2; i++ )
    {
    	printf("%s - %s\n", dic[i][0], dic[i][1]);
    }

    return 0;
}

This is your original code (in code tags, please use them):

char *dic[][40] = {
"atlas", "A volume of maps.",
"car", "A motorized vehicle.",
"telephone", "A communication device.",
"airplane", "A flying machine.",
"", "" /* null terminate the list */
};

The square brackets here: dic[][40], are not necessary.

You have an array of pointers to a 2D array of char's.

That's not quite what you need though.You just need:

an array of pointers to a row of char's (a row of char's is a 1D array of char's).

So, it should be:

char *dic[40] = {
"atlas", "A volume of maps.", "car", "A motorized vehicle.",
"telephone", "A communication device.", "airplane", "A flying machine.", ""
};
//the number of strings per line above, doesn't matter at all.

C will count the number of items in this array (the number of strings), and assign the correct number of pointers to handle it (if possible). Also, C will give each pointer, the proper address, so even though the strings are not the same size, the pointer for each string will point right to the first char in it's string.

It might be easier to think of this, like this:

for(i=0;array[i];i++)
  printf("%s", array[i]);

This is not a true 2D array, since the first dimension is all pointers, but pointers and arrays have many shared characteristics - to the point where you start thinking that arrays *are* pointers with "syntactic sugar", to make them easier to work with.

Thanks Adak, I understood somewhat. But to still be completely clear I decided to learn pointers in depth. I have a book that is completely dedicated to the pointers in C. I will update about any insight & great things I will learn.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.