• 10
• 12
• 12
• 14
• 16

# simple array question

This topic is 4775 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hi. i'm trying to keep a pointer to a 2d array. here's what i'm doing:
#include <stdio.h>

char g_Test[5][32] =
{
"One",
"Two",
"Three",
"Four",
"Five",
};

int main()
{
char **pTest;

pTest = g_Test;

for(int i = 0; i < 5; i++)
{
printf("%s\n", pTest);
}

return 0;
}


but this is giving me some errors. anyone know how to do this? thanks!

##### Share on other sites
You are very close! All you need to do is make char g_Test[5][32] = into char* g_Test[5] = because of the variable lengths of the strings.

##### Share on other sites
thanks! that works. but, isn't that incorrect with respect to the pointer? don't i have to specifiy the storage value (32) for the strings so that it actually reserves memory for them? becuase i know that this is incorrect:

char *text = "Text";

right?

##### Share on other sites
Quote:
 Original post by RegularKidthanks! that works. but, isn't that incorrect with respect to the pointer? don't i have to specifiy the storage value (32) for the strings so that it actually reserves memory for them? becuase i know that this is incorrect:char *text = "Text";right?

That is "correct" as in "legal" but it is advised against strongly. What you should take a look into is using the Standard C++ Library for the use of the string class. For example:
#include <string>std::string text = "Text";

If you still want to use the other style, then you can do something like this:
char text[32];sprintf( text, "Text" );

But that is kind of dangerous as well. Best bet is using the string class. For a reference take a look at this. As for the entire lirary, which is quite big, take a look at this.

 Ehhh just read-read my post. I am kind of out of it right now so I think I totally missed the mark here. Oh well, someone else can explain better alternatives [lol].

##### Share on other sites
It's kind of right but they should all be const char *.

They're pointing to string constants, which are a static part of the program and shouldn't be changed. Changing them can cause crashes (they are often stored in read-only memory) or at least cause strange things to happen (duplicate strings are often stored in the same location, so changing one would change all of them).