Tuesday, July 14, 2009

What type should I use to store an array of strings in a class in Visual Studio 2005 C++ ?

I have used char name[20]; to store names before but this is an array itself, correct?





name = "myname"; Does this variable still use 20 bytes? Is a NULL inserted after the last letter of the name in this case?





Maybe a two dimensional char would be best here?





Like char name[20][100]; to store 100 different names?





THanks for helping this newb!

What type should I use to store an array of strings in a class in Visual Studio 2005 C++ ?
yes, char name[20][100] will store 100 names





from what I saw in my debug I typed in "mike"





and it gave me





0-3 were for m i k e


4 was '0'


and the rest were "-52" not sure what to make of it though
Reply:First of all, you're using C++ which has a standard string class. Example of using it:





#include %26lt;string%26gt;


using namespace std;


string name = "My name";





Once you're using the std::string class, you will only need a one-dimensional array (or vector or linked list).





It depends on how many strings you want to store and how you want to access them. If you use an array, you will have to resize them manually when you run out of space, or you will end up wasting space.





The standard library for C++ also includes vectors (arrays that automatically resize themselves).





You can also use linked lists to never waste space. But the problem with linked lists is that you have to look through most of them to find the particular string you want.


No comments:

Post a Comment