Ivan  Petrov
Ivan Petrov

Reputation: 155

Multidimensional array calculating

I've got an array of arrays of TCHAR, where I store file extension.

TCHAR *extens[] = { L".*", L".txt", L".bat" };

In order to go through it, I'm calculating it's length.

int extCount = sizeof(extens) / sizeof(TCHAR);

But for some reason the extCount's value is 2. I think the problem is because this is wrong calculation method, but then, how to count the number of elements ("words") in this array correctly?

UPD: I'am passing this array to function:

void func(TCHAR *path, TCHAR **names, TCHAR **extensions);

When i'am calculating this array lenght outside function it show correct number, but inside it always workis wrong (returns 2 or 1).

UPD2: I tried to redeclare array like this:

TCHAR *extens[] = { L".txt", L".bat", L".txt", NULL };

And now inside function i'am doing something like that:

TCHAR **p = extensions;
    int extCount = 0;
    while (*p != NULL)
    {
        extCount++;
        *p++;
    }

    extCount = cnt;
    wsprintf(temp, L"%d", cnt);
    MessageBox(NULL, temp, temp, MB_OK);

It works, but looks like its not so effective, because of walking two arrays, isn't it?

Upvotes: 0

Views: 96

Answers (3)

JorenHeit
JorenHeit

Reputation: 3997

First of all, you have an array of pointers so you need

extCount = sizeof(extens) / sizeof(TCHAR*);

to calculate its size. However, this assumes that extens is still of an array-type. Once you pass it to a function expecting a TCHAR**, the array will decay to a pointer and its size information will be lost.

I think your best option would be to rewrite this in terms of std::string and std::vector. This is C++ so you might as well use its facilities. If this is not possible for any reason, and the arrays are known at compile time, you could templatize the function on array-sizes:

template <size_t N, size_t M>  
void func(TCHAR *path, TCHAR *(&names)[N], TCHAR *(&extensions)[M]);

The syntax is a bit messy maybe. For example, TCHAR *(&names)[N] is read as: "names is a reference to an array of N pointers to TCHAR". Here, the size N is deduced by the compiler as long as you don't let the array decay to a plain pointer.

Upvotes: 1

Nasser Al-Shawwa
Nasser Al-Shawwa

Reputation: 3663

You have an array of TCHAR*.

To get the length of the following array:

TCHAR *extens[] = { L".*", L".txt", L".bat" };

You need to use:

sizeof(extens) / sizeof(TCHAR*)

Upvotes: 1

paper.plane
paper.plane

Reputation: 1197

TCHAR *extens[] is an array of pointers of type TCHAR. And the size of such an array will be array_length * sizeof(pointer)).

Note: sizeof(pointer) on a system will be same for all datatypes.

Upvotes: 1

Related Questions