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?
A C-style string is simply an array of characters that uses a null terminator. A null terminator is a special character ('\0', ascii code 0) used to indicate the end of the string. More generically, A C-style string is called a null-terminated string.
We can take string input in C using scanf(“%s”, str).
C does not have a built-in string function. To work with strings, you have to use character arrays.
The strchr function returns a pointer to the first occurrence of character c in string or a null pointer if no matching character is found.
C strings are "nul-terminated" which means there is an additional byte with value 0x00 at the end. When you call sizeof(s), you are getting the size of the entire buffer including the nul terminator. When you call strlen(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 s and put a nul terminator somewhere other than at the end, then sizeof(s) would still be 7 (because that's a static property of how s is declared) but strlen(s) could be somewhat less (because that's calculated at runtime).
No, all trings in C are terminated by the null character (ascii 0). So s is actually 7 bytes
s i z e m e \0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With