tags:

views:

156

answers:

5
const static char *g_szTestDataFiles[] = {
    ".\\TestData\\file1.txt",
    ".\\TestData\\file2.txt",
    ".\\TestData\\file3.txt",
    ".\\TestData\\file4.txt",
    ".\\TestData\\file5.txt",
    ".\\TestData\\file6.txt" 
};

Is there way to programmatically determine how many items is in that thing? I could always do #define NUM_DATA_FILES 6 or const int NUM_DATA_FILES=6 but is there a better way? I don't think there is, but this seems too basic and I want to make sure i'm not forgetting something . . .

+11  A: 
const static char *g_szTestDataFiles[] = {
".\\TestData\\file1.txt",
".\\TestData\\file2.txt",
".\\TestData\\file3.txt",
".\\TestData\\file4.txt",
".\\TestData\\file5.txt",
".\\TestData\\file6.txt",
NULL

};

Now iterate one string after each other till you find NULL.

EDIT: Glen is right though, you should use a std::vector here rather than c style *[]

Arkaitz Jimenez
+1 for being technically correct. Though as this is tagged C++ is it worth point out that the OP should be using idiomatic C++, i.e. std::vector instead of arrays
Glen
+7  A: 

You can use:

sizeof(g_szTestDataFiles) / sizeof(g_szTestDataFiles[0])

Note that this method only works if g_szTestDataFiles is an array and not a pointer.

Greg Hewgill
+6  A: 

Arkaitz has given you the preferred way of handling this, but as we're talking about an array of const char * here, you should be able to do the following:

int size = sizeof(g_szTestDataFiles) / sizeof(g_szTestDataFiles[0]);
Timo Geusch
Great man thanks!! I was pretty sure there was a way to do that I just couldn't remember it lol. Thanks!!
cchampion
+6  A: 

If you are indeed using C++, you might want to use a const vector<string> which gives you some nice abstraction and methods.

lhahne
yeah good idea.
cchampion
It's a good idea, but in the current version of C++, you can't declare a `const std::vector<string>()` at global scope and populate it accordingly, unless you want the vector to be empty or consist of multiple copies of one string. C++0x fixes this and allows vector literals.
Adam Rosenfield
+2  A: 

You can use this function:

template <typename T, std::size_t N>
inline std::size_t array_size(T (&)[N]) { return N; }

like here:

std::size_t sz = array_size(g_szTestDataFiles);

Anyway, you should follow lhahne advice and use std::vector.

fnieto