Advertisement

using sizeof()

Started by July 17, 2001 02:11 AM
3 comments, last by Xtreme 23 years, 7 months ago
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?
Yes! There are kangaroos in Australia but I haven't seen them...yet
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.

_______________________________
"To understand the horse you'll find that you're going to be working on yourself. The horse will give you the answers and he will question you to see if you are sure or not."
- Ray Hunt, in Think Harmony With Horses
ALU - SHRDLU - WORDNET - CYC - SWALE - AM - CD - J.M. - K.S. | CAA - BCHA - AQHA - APHA - R.H. - T.D. | 395 - SPS - GORDIE - SCMA - R.M. - G.R. - V.C. - C.F.
Advertisement
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.
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


Yes! There are kangaroos in Australia but I haven't seen them...yet
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.

This topic is closed to new replies.

Advertisement