Difference between string size in Standard C and C++

Asked

Viewed 62 times

1

I compiled the following code in C Standard and C++:

#include <stdio.h>
#include <string.h>

char string[5] = "hello";

int main(void)
{

   printf("string tem %lu bytes\n", sizeof(string));

   for (int i = 0; i < 6; i++)
   {
      printf("string[%d]: %d \n", i, string[i]);
   }

   return 0;
}

In Standard C it compiles normally, but in C++ it gives error when compiling.

What is the difference between C and C++ to give this error?

output in C++:

entradas.cpp:4:18: error: initializer-string for array of chars is too long [-fpermissive]
    4 | char string[5] = "hello";
      |                  ^~~~~~~

Intellisense vs Coded Warning:

um valor de tipo "const char [6]" não pode ser utilizado para inicializar  uma entidade do tipo "char [5]"C/C++(144)

Complementing, I compiled smoothly in standard C, and in c++ using the variable declaration in this way:

char string[5] = {'h','e','l','l','o'};

I used vsCode (code Runner) and Replit.

  • Note that in a char[6] the number of positions/elements/items/houses is 6 even. The position/index goes from 0 to 5, which is where the \0, that is, up to 5 letters fit in the remaining boxes.

  • Why then, using the examples at the end of the question, in C and C++ separating the letters into characters, compile without error message?

  • 1

    The question doesn’t seem very coherent, the code shows one thing, the messages show things that can’t appear in that code. We don’t even really know what’s going on.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.