• Popular Now

• 13
• 18
• 19
• 27
• 10

Archived

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

sizeof( char[4] ) = 4? Why?

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

Recommended Posts

If you do:
char text[4];
strcpy( text, "ABCD" );

then it's actually the following?
text[0] = 'A';
text[1] = 'B';
text[2] = 'C';
text[3] = 'D';
text[4] = '\0';

Right? When I check strlen(text), it shows up as 4, which is understandable because there are 4 characters. But when I do sizeof(text), I would expect to see 5 (i.e. 5 bytes), because thats how long text memory allocation actually is. But it comes up as 4. Why? [edited by - PugPenguin on April 18, 2003 12:56:52 PM]

Share on other sites
It actually IS 4 characters.
Your strcpy is overwriting the bounds of the array.

Share on other sites
Because you declared it to be of size 4. Make it be a size of 5 and you''ll be way better off.

Share on other sites
quote:
Original post by TravisWells
It actually IS 4 characters.
Your strcpy is overwriting the bounds of the array.

Beat me to it. Darn you!

Share on other sites
char text[4];

means you can access

text[0]
text[1]
text[2]
text[3]

NOT text[4]

[edited by - en dum en on April 18, 2003 1:01:04 PM]

Share on other sites
Doh. ah yes I do remember, it''s length of string + 1 when allocating memory for strings.

Thats cruel...

Share on other sites
Far to cruel, use C++ strings hehe. Saves you so many headaches in the long run.

Share on other sites
quote:
Original post by Illumini
Far to cruel, use C++ strings hehe. Saves you so many headaches in the long run.

Yeah I do that! But, strange though it may be, I love getting involved with technicality and theoretical framework of things (got physics degree... that sort of background), so I find myself bogged down in (relatively) useless facts and questions and lose sleep if it goes on for too long

Share on other sites
If you are getting the sizeof(text)=4 this is correct because it is the size of the address text. text is a pointer to the beginning of the character array and under most pentium machines pointer are 4 bytes long or 32 bits try getting the sizeof(text[0]) and that should equal 1

Share on other sites
quote:
Original post by iamgod
If you are getting the sizeof(text)=4 this is correct because it is the size of the address text.

I''m pretty sure that is incorrect.

In cases where the memory allocation is done by fixed-array decleration (as opposed to dynamic memory allocation), it does return the length of the WHOLE allocated buffer, so in above case sizeof(text) is 4 because of 4 x 1byte = 4 bytes, and not because the pointer itself is 4 bytes long.

The bit that boggled me was not being able to use [4]th part of text[]... it stops at text[3] element when I declare text[4]