1

While using Turbo c++ initializing array of char variable getting error code as follows

int gd=DETECT,gm,i,d=0,x,y;
char s[12]={"3","4","5","6","7","8","9","10","11","12","1","2","\0"};
initgraph(&gd,&gm,"..\\BGI");

but while used to initialize s[12][3], the initializer list works fine!

4
  • 1
    Yes, so? {"3","4","5","6","7","8","9","10","11","12","1","2","\0"}; is not an array of characters. What else did you expect to happen? Also FYI, Microsoft DOS has no future, get a modern compiler. Commented Nov 28, 2017 at 7:34
  • Is this C or C++? Commented Nov 28, 2017 at 7:42
  • Bathsheba it was c program in turbo c++. solved the problem. Thanks to everyone Commented Nov 28, 2017 at 7:43
  • A bit of pub quiz trivia: '3' & c. are int types in C, and char types in C++. Commented Nov 28, 2017 at 7:45

3 Answers 3

3

There is a difference between "3" and '3'.

  • "3" is a string literal
  • '3' is a character constant (to nitpick: integer character constant)

here, to initialize an array of char type, you seem to need (brace-enclosed) list of character constants, not strings.

but while using s[12][3] works fine

Well, there you're initializing arrays.

Moral of the story: When in doubt, check the data types!!

Sign up to request clarification or add additional context in comments.

Comments

1

You need to change:

char s[12]={"3","4","5","6","7","8","9","10","11","12","1","2","\0"};

to

char s[13]={'3','4','5','6','7','8','9','10','11','12','1','2','\0'};

As char array elements should be char literals not string literals

Comments

1

You are trying to store chars, not strings, so why do you use double quotes?

"a" is a string, 'a' is a character.

What you actually want to store is strings, and for that you need a 2D array, like this:

s[12][3] = {"3","4","5","6","7","8","9","10","11","12","1","2"};

You cannot express 10 as a single character, I mean '10' does not exist. Single characters are from 0 to 9 when it comes to digits. For that reason, you need a string for 10, like this "10".

Now, you need the second dimension of your array to be 3, because the string "10" (for example) is a null-terminated string, thus 2 characters for its actual contents, plus one for the null-terminator, gives as 3.


PS: Turbo-C++ is an ancient compiler. Upgrade to GCC or anything else, really.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.