Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get some assistance with this C style string in C++?

Tags:

c++

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?

like image 682
quakkels Avatar asked Oct 08 '11 23:10

quakkels


People also ask

What is the C style character string?

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.

How can I get a string in C?

We can take string input in C using scanf(“%s”, str).

Does C support string data type?

C does not have a built-in string function. To work with strings, you have to use character arrays.

How do you check if a string contains a specific character in C?

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.


2 Answers

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).

like image 187
Greg Hewgill Avatar answered Sep 26 '22 20:09

Greg Hewgill


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
like image 30
Sodved Avatar answered Sep 25 '22 20:09

Sodved