Compile C ++ code in c mode

Below 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 perceives this as the C code itself.

I tried extern "C", which did not help.

+4
source share
5 answers

Although this does not help your problem, you can choose the language to compile. With the gcc flag -x followed by the language. Like gcc -xc something.cpp ... will use the c compiler to compile.

0
source

The character string "12" holds 3 places in C ++ (in C, too, BTW). You will need another char to complete '\0' .

 char str[2][3]= { "12", "12"}; 
+14
source

It will "match"

 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 place to terminate the null character

Equivalent:

 char str[2][3]= { { '1', '2', '\0' }, { '1', '2', '\0' } }; 
+10
source

C ++ is a more strict language than C. The problem is that you create an array containing two-character arrays, and then assign each submatrix three characters (the sequence '1' , '2' and the string delimiter '\0' ).

An array must be declared as follows:

 char str[2][3]= { "12", "12"}; 

The C compiler does not specify this and skips the string delimiter, so your printf statement will most likely dump garbage after the string.

+1
source
 #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 a version that will work in C ++ ....

0
source

Source: https://habr.com/ru/post/1382659/


All Articles