1

In C it has come to attention that there is a difference between these 2 specified syntax. Observe

 char test[5] = {"c", "o", "o", "l", "\0"}; // with quotation

bring about error:

error: (near initialization for 'test')
error: excess elements in char array initializer
error: (near initialization for 'test')
error: excess elements in char array initializer
error: (near initialization for 'test')
error: excess elements in char array initializer
error: (near initialization for 'test')

Where as

char test[5] = {'c', 'o', 'o', 'l', '\0'}; // with apostrophe

Compiles finely. What is the cause of this?

user3818650
  • 581
  • 1
  • 7
  • 19

5 Answers5

2

In C, when you are using single quotes then it means a character and a double quotes means string literal. And since you declared your array as char hence it cannot store string in that.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

"x" is not a character, Its a string literal. It is same as an array of two characters 'x' and '\0'.

I think of it like this:

       _ _ _ _ _
"x" => |'x'|'\0'| 
       - - - - -  
Raman
  • 2,735
  • 1
  • 26
  • 46
2

The elements in this array are characters (1 byte each):

char test[5] = {'c', 'o', 'o', 'l', '\0'};

This is a null-terminated C string. It's represented exactly the same way in memory. It consists of exactly 5 bytes: the letters "cool", and the terminating null character:

char test2[5] = {"cool"};

And this consists of two bytes:

char test3[] = "c";

Your original example is an array of 2-byte strings. Unlike the previous examples, it's actually a 2-level array. You must declare it as such:

char *test[] = {"c", "o", "o", "l", "\0"};

paulsm4
  • 114,292
  • 17
  • 138
  • 190
2
char test[5] = {'c', 'o', 'o', 'l', '\0'}; // with apostrophe

is the correct syntax because, as you have declared, test is an array of characters which can store 5 characters.

char* test[5] = {"c", "o", "o", "l", "\0"}; // with quotation

This is acceptable, since you are declaring that test is an array of pointers to character strings.

Run the following code in ideone.com and see.

#include <stdio.h>

int main(void) {
// your code goes here

char* teststring[5] = {"c", "o", "o", "l", "\0"}; // with quotation

char testchar[5] = {'c', 'o', 'o', 'l', '\0'};
printf("%s\n", teststring[2]);

printf("%c\n", testchar[2]);

return 0;
}
a3.14_Infinity
  • 5,653
  • 7
  • 42
  • 66
1

In C,

Two single quotes, ', are used to represent a character constant.
Two double quotes, ", are used to represent a string literal.

A character constant can represent one character only. 'ab' is not a valid character constant.

A string literal can contain multiple characters.

R Sahu
  • 204,454
  • 14
  • 159
  • 270