2

I am new to C. I just want to know why initializing the array of int with int is working and why initializing an array of char with char is not working. Or am I wrong thinking that "1" is a char?

#include <stdio.h>

int main()
{
     int incoming_message_test[2] = {1, 2}; // why does this work?
     char incoming_message[2] = {"1", "2"}; // why does this not work?
   
     return 0;
}
2
  • 2
    "1" is not a char, it's an array of two chars. Commented Nov 24, 2019 at 21:20
  • How do you know it does not work? You should include the error message. Commented Nov 24, 2019 at 21:24

5 Answers 5

3

You must change "1", "2" with '1', '2'

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

Comments

2

This question was a bit deeper than I first saw.

The first works because char is an integer type, and this code is perfectly valid:

int x = 42;
char c = x;

However, string literals cannot be converted that way. Instead of "1", use '1'.

Comments

2

In C:

  1. 'c' is a char
  2. "c" is a string, meaning an array of N+1 chars. In this case char 'c' followed by string terminator '\0'.

Comments

1

In C, a character literal contains one character that is surrounded with a single quotation ( ').

So instead of "1", "2", use '1', '2'.

Comments

1

Or am I wrong thinking that "1" is a char ?

Yes.

For single characters, use single quotes.

So, define you array like so:

char incoming_message[2] = {'1', '2'};

Single-quote character literals have the type char, while double-quote string literals have the type char * (a pointer (address) to a char).

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.