character string

In C++, does
char c1[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N' };
and
char c2[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N','/0' };
mean the same? and is c1[] syntactically right?
they do not mean the same.
The first one creates and initializes an array of 13 char

Assuming you meant '\0' rather than the multi-character literal '/0', the second one creates and initializes an array of 14 char, which also happens to satisfy the requirements for a C string.
Thanks cubbi, now DOES
compiler add a '\0' again to c2[] internally? and is it correct practice to declare like c1[] or like c2[] ?

Last edited on
Nothing happens "internally". Both declarations are "correct practice", but since they declare different things, they are used differently.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstring>
int main()
{
   char c1[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N' };
   char c2[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N','\0' };

   std::cout << "c1's size: " << sizeof c1 << " c2's size: "  << sizeof c2 << '\n'
             << "c2 also happens to be a C string, strlen(c2)=" << std::strlen(c2) << '\n';
}

demo: http://coliru.stacked-crooked.com/a/d5aa6d799302f43a
Last edited on
Yes a string literal is null terminated. Preferable to write them like this:

1
2
char c1[] = "MY PROFESSION";
char c2[] = {"MY" " " "PROFESSION"};
Thanks :) I have a similar doubt which i have explained better in http://www.cplusplus.com/forum/general/127953/ please help ! thanks in advance
Topic archived. No new replies allowed.