Possible Duplicate:
Sizeof an array in the C programming language?
I have an array of char and I want to process it in a function, I tried code like this:
int main(){
char *word = new char [5];
/*here we make this word
....
*/
process(word);
puts(word);
}
void process(char *word){
int sizeOfWord = sizeof(word)-1;
/* here is cycle that process the word, I need it lenght to know how long cycle must be
.....
*/
}
But I can’t get the length of array with sizeof. Why? And how can I get that?
You can’t. With a pointer, there is no way to know the size.
What you should do is, pass the length of
wordto yourprocessalso.You should know that there is a difference between arrays and pointers. Arrays are indeed a number of elements and therefore
sizeofof the array gives its size (in bytes). A pointer on the other hand is just an address. It may not even point to an array. Since thesizeofoperator is computed at compile time (except for variable length arrays), it cannot know what you mean.Think of this example:
Now, knowing that
sizeofin this case is computed at compile time, what value do you think it should get?5?10?Side note: It looks like you are using this array as a string. In that case, you can easily get its length with
strlen.