Following is my code saved as .cpp file and .c file
in .c it compiled fine, but threw the following error in .cpp
test.cpp:6: error: initializer-string for array of chars is too long
test.cpp:6: error: initializer-string for array of chars is too long
#include< stdio.h>
int main()
{
char str[2][2]= { "12", "12"};
int i;
for(i=0; i<2; i++)
printf("%d %s\n", i, str[i]);
return 0;
}
Is there any compiler directive or anything so that the c++ compiler takes this as C code itself.
I tried, extern "C", which didn't help.
The character string "12" hold 3 places in C++ (In C too, BTW). You need one more char for the terminating '\0'
.
char str[2][3]= { "12", "12"};
This would 'fit'
char str[2][2] = {
{ '1', '2' },
{ '1', '2' }
};
But you want this: https://ideone.com/wZB8F
char str[2][3]= { "12", "12"};
Otherwise, there is no room for the terminating null
character
Equivalent:
char str[2][3]= { { '1', '2', '\0' },
{ '1', '2', '\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