2

Is the type of a string, like "hello, world" a char * or const char *, as of C99? I know that in C++ it is the latter, but what about in C?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523

4 Answers4

6

String literals in C are not pointers, they are arrays of chars. You can tell this by looking at sizeof("hello, world"), which is 13, because null terminator is included in the size of the literal.

C99 allows string literals to be assigned to char *, which is different from C++, which requires const char *.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • well to be fair, every array of `n` length of `s size objects in C is actually a ponter to `n` consecutive `s` size data in memory. But JoachimPileborgs' answer discusses this in more detail. – erik258 Dec 24 '15 at 16:38
  • 4
    @DanFarrell Although array's name is interpreted as a pointer to its initial element in many contexts, saying that an array *is* actually a pointer would not be entirely correct. Contexts where array's name is not interpreted as a pointer to array's initial element are `sizeof` and pointer arithmetics. – Sergey Kalinichenko Dec 24 '15 at 16:45
  • ah, nice clarification. – erik258 Dec 24 '15 at 16:50
2

String literals are of type char[N] in C. For example, "abc" is an array of 4 chars (including the NUL terminator).

P.P
  • 117,907
  • 20
  • 175
  • 238
1

The type of a string literal in C is char[]. This can directly be assigned to a char*. In C++, the type is const char[] as all constants are marked with const in C++.

Shadowwolf
  • 973
  • 5
  • 13
0

A character literal is always an array of read-only characters, with the array of course including the string terminator. As all arrays it of course decays to a pointer to the first element, but being read-only makes it a pointer to a const. It originated in C and was inherited by C++.

The thing is that C99 allows the weaker char * (without const) which C++ (with its stronger type system) does not allow. Some compilers may issue a warning if making a non-constant char * point to a string literal, but it's allowed. Trying to modify the string through the non-const char * of course leads to undefined behavior.

I don't have a copy of the C11 specification in front of me, but I don't think that C11 makes this stronger.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621