user5405648
user5405648

Reputation:

What is a literal string & char array in C?

Firstly, I included C++ as C++ is just a parent of C, so I'm guessing both answers apply here, although the language I'm asking about and focusing on in this question is C, and not C++.

So I began reading the C book 'Head First C' not so long ago. In the book (page 43/278) it will answer a question for you. Are there any differences between literal strings and character arrays.

I was totally thrown by this as I didn't know what a literal string was. I understand a string is just a array of characters, but what makes a 'string' literal? And why is it mentioning string in C if C doesn't actually provide any class (like a modern language such as C# or Java would) for string.

Can anyone help clean up this confusion? I really struggle to understand what Microsoft had to say about this here and think I need a more simple explanation I can understand.

Upvotes: 1

Views: 5116

Answers (2)

chux
chux

Reputation: 153498

What is a literal string & char array in C?

C has 2 kinds of literals: string literals and compound literals. Both are unnamed and both can have their address taken. string literals can have more than 1 null character in them.

In the C library, a string is characters up to and including the first null character. So a string always has one and only one null character, else it is not a string. A string may be char, signed char, unsigned char.

//          v---v string literal 6 char long
char *s1 = "hello";
char *s2 = "hello\0world";
//          ^----------^  string literal 12 char long

char **s3 = &"hello";  // valid

//        v------------v  compound literal
int *p1 = (int []){2, 4};
int **p2 = &(int []){2, 4};  // vlaid 

C specifies the following as constants, not literals, like 123, 'x' and 456.7. These constants can not have their address taken.

int *p3 = &7; // not valid

C++ and C differ in many of these regards.


A chararray is an array of char. An array may consist of many null characters.

char a1[3];          // `a1` is a char array size 3
char a2[3] = "123";  // `a2` is a char array size 3 with 0 null characters 
char a3[4] = "456";  // `a3` is a char array size 4
char a4[] = "789";   // `a4` is a char array size 4
char a5[4] = { 0 };  // `a5` is a char array size 4, all null characters

The following t* are not char arrays, but pointers to char.

char *t1;
char *t2 = "123";
int *t3 = (char){'x'};  

Upvotes: 5

HolyBlackCat
HolyBlackCat

Reputation: 96266

A string literal is an unnamed string constant in the source code. E.g. "abc" is a string literal.

If you do something like char str[] = "abc";, then you could say that str is initialized with a literal. str itself is not a literal, since it's not unnamed.

A string (or C-string, rather) is a contiguous sequence of bytes, terminated with a null byte.

A char array is not necessarily a C-string, since it might lack a terminating null byte.

Upvotes: 8

Related Questions