Reputation: 63
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.
Upvotes: 4
Views: 411
Reputation: 6290
#include< stdio.h>
int main()
{
char str[][3]= { "12","12"};
int i;
for(i=0; i<2; i++)
{
printf("%d %s\n", i, str[i]);
}
return 0;
}
is the version that will work in C++....
Upvotes: 0
Reputation: 9476
Although it won't help your problem, you can select language to compile. With gcc it's -x flag, that needs to be followed by language. Like gcc -x c something.cpp ... will use c compiler to compile.
Upvotes: 0
Reputation: 393709
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' } };
Upvotes: 10
Reputation: 409432
C++ is a stricter language than C. The problem is that you create an array containing of arrays of two characters, then assign each sub-array three characters (the sequence '1'
, '2'
and the string terminator '\0'
).
The array should be declared like this:
char str[2][3]= { "12", "12"};
The C compiler doesn't flag for this, and skips the string-terminator, so your printf
statement will most likely print garbage after the string.
Upvotes: 1
Reputation: 37467
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"};
Upvotes: 14