Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile c++ code in c mode

Tags:

c++

c

c-mode

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.

like image 675
user1061410 Avatar asked Nov 28 '22 03:11

user1061410


2 Answers

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"};
like image 152
Didier Trosset Avatar answered Dec 05 '22 11:12

Didier Trosset


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' } };
like image 44
sehe Avatar answered Dec 05 '22 10:12

sehe