Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing an array and using sizeof

Status
Not open for further replies.

endfx

Technical User
Jun 14, 2006
6
0
0
CA
Please consider the following code:

int main (int argc, char *argv[])
{
char s1[9] = "abcdefghi";
int length = sizeof(s1);
printf("Size of s1: %d\n", length);

rev1(s1);
}

void rev1(char *s)
{
int length = sizeof(s)
printf("Size of s: %d\n", length);
}

When I run this program I get
Size of s1: 9
Size of s: 4

It doesn't matter what size I use for the s1 array, I always get 4 for the array size in rev1. I don't understand why s isn't 9. Why is it 4?

Can someone help me out?

Thanks!

 
As Salem's post suggests, the argument s, in the definition of rev1, is a pointer. As such, the compiler evaluates sizeof(s) to be the size of a pointer, 32 bits or 4 octets. If you really need to know the length of the array of char's that s points to, you could use e.g.

Code:
int length = (int) strlen( s );


Hope this helps.

Greg Hansen
 
You have also made the common mistake of not counting the terminator. "abcdefghi" is actually 10 characters. You need to count the terminator. What actually happens is the terminator clobbers the stack. As long as you don't go over the stack frame, there isn't a crash. Once you go over the stack frame it just crashes. You'll start wondering why it works for some but not for others.

The declaration should be one of the following
Code:
    char s1[] = "abcdefghi";
    char s1[10] = "abcdefghi";
    char* s1 = "abcdefghi";
 
> What actually happens is the terminator clobbers the stack.
No it doesn't. The \0 is quietly dropped and it just becomes an ordinary array of chars.

It is however an invalid string as far as most string functions are concerned, because it lacks the \0 terminator.

Such an array initialiser would be invalid in C++, since there is no room for the \0.

Just another one of those C isn't C++ differences.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Oh well, it did clobber the stack on the Whitesmiths, Zortech and MS compilers in the late 80s. I haven't looked at it since. Probably the modern compilers follow the rules more rigidly. Took me ages to figure out why a variable had the wrong initial value.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top