I’m trying to understand un-managed code. I come from a background of C# and I’m playing around a little with C++.
Why is that this code:
#include <iostream>
using namespace std;
int main()
{
char s[] = "sizeme";
cout << sizeof(s);
int i = 0;
while(i<sizeof(s))
{
cout<<"\nindex "<<i<<":"<<s[i];
i++;
}
return 0;
}
prints out this:
7
index 0:s
index 1:i
index 2:z
index 3:e
index 4:m
index 5:e
index 6:
????
Shouldn’t sizeof() return 6?
C strings are “nul-terminated” which means there is an additional byte with value
0x00at the end. When you callsizeof(s), you are getting the size of the entire buffer including the nul terminator. When you callstrlen(s), you are getting the length of the string contained in the buffer, not including the nul.Note that if you modify the contents of
sand put a nul terminator somewhere other than at the end, thensizeof(s)would still be 7 (because that’s a static property of howsis declared) butstrlen(s)could be somewhat less (because that’s calculated at runtime).