#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;
}
simple array question
hi. i'm trying to keep a pointer to a 2d array. here's what i'm doing:
but this is giving me some errors. anyone know how to do this? thanks!
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.
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?
char *text = "Text";
right?
Quote:Original post by RegularKid
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?
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.
[edit] 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].
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).
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).
No, that's fine. As soon as the compiler sees "Text", it knows to create a string literal somewhere in the static storage of the application. Then it points the pointer at that.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement