I need to find the number of elements in an array passed into a function. The problem is in this case, sizeof() returns the size of the pointer itself. It only does this when passed through to a function. So here is that function:

bool matchWord(TWORD *wordList, TWORD *word, char *str)
{
	for(int i = 0; i < sizeof(wordList) / sizeof(wordList[0]); i++)
	{
		if(_stricmp(wordList[i]->str, str) == 0)
		{
			word->str = wordList[i].str;
			word->id = wordList[i].id;
			word->pos = wordList[i].pos;
			return true;
		}
	}
	return false;
}

Here is the array definition if you need to look at it:

TWORD *wordList = new TWORD[2];
wordList[0].setValues("move", WORD_MOVE, POS_VERB, -1);
wordList[1].setValues("north", WORD_NORTH, POS_NOUN, -1);

And although you really shouldn't need to look at is for this problem, here is the definition of the TWORD class:

class TWORD
{
	public:
		char *str;
		int id;
		int pos;
		int index;

		TWORD();
		TWORD(char *str, int id, int pos, int index);
		void setValues(char *str, int id, int pos, int index);
		char *posToString();
		char *toString();
};

TWORD::TWORD()
{
	this->str = NULL;
	this->id = 0;
	this->pos = 0;
	this->index = -1;
}

TWORD::TWORD(char *str, int id, int pos, int index)
{
	this->str = str;
	this->id = id;
	this->pos = pos;
	this->index = index;
}

void TWORD::setValues(char *str, int id, int pos, int index)
{
	this->str = str;
	this->id = id;
	this->pos = pos;
	this->index = index;
}

char *TWORD::posToString()
{
	switch(this->pos)
	{
		case POS_NOUN:
		{
			return "noun";
		} break;
		case POS_VERB:
		{
			return "verb";
		} break;
	}
	return "unknown";
}

char *TWORD::toString()
{
	char *str = new char[100];
	sprintf(str, "String: %s\nID: %d\nPos: %s\nIndex: %d\n", this->str, this->id, this->posToString(), this->index);
	return str;
}

Please don't suggest the vector template, I usually stick to straight C and this is about as far away from that as I am really willing to get.

Recommended Answers

All 2 Replies

Unfortunately what you are trying to do can't be done directly.

The only time the sizeof/sizeof idiom works is on the original array[] variable. Pointers and function arguments etc don't know anything about the original array...

The two usual solutions are:

  1. Pass the size of the array as an argument.
  2. Place a null value at the end of the array (just like a string ends with '\0').

Sorry there isn't a better answer...

I kind of thought as much. Well thanks anyway.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.