Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

using sizeof()

This topic is 6151 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey ppl, if i defined an array of chars like this: char elements[] = {"hello"}; and then call sizeof(elements) i get 6 which is correct. Now, if i send the elements to a function via a pointer and then call sizeof(elements) I get 4. (which is the size of the pointer) How can I get the size of the contents of the pointer? Is there a way to retrieve it without having to pass in the length of elements when calling a function? Any ideas?

Share this post


Link to post
Share on other sites
Advertisement
Your function (by virtue of being a function) can''t make the assumption that it is dealing with statically initialized strings.

So, you''re going to have to do it the old fashioned way: strlen ().

Or, declare a global var which is initialized to the length of the string before entering the function, and then access that global var from within the function. A decidedly ugly way of doing it, but faster than strlen () if you have hardcoded string lengths as your example has.

Share this post


Link to post
Share on other sites
bishop_pass has explained what you need to do. sizeof is processed at compile time, so you can''t find out the size of the contents of a pointer because the compiler can''t know what''s going to be pointed to by the pointer until run time.

Share this post


Link to post
Share on other sites
so are you suggesting to use either strlen() or declare a global var instead?

Update:
strlen() works!! thanks guys.

hey Midnight, but the same problem is for strlen() too. It doesnt know the length of the string pointed to by the pointer
during compile time.

Edited by - Xtreme on July 17, 2001 9:55:14 PM

Share this post


Link to post
Share on other sites
strlen''s whole purpose is to determine the length of a string, given a char pointer to the first character. For strlen to function properly (since it just iterates char pointers starting at the one you passed until it sees a null character) you have to make sure all your strings are null terminated (with the ''\0'' character). String literals such as your "hello" will automatically be null terminated for you by the compiler. If the string itself is generated at runtime, keep this null termination in mind or strlen and other such string functions that expect the null termination will either give you incorrect results or crash your program altogether.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!