Jeremy Rosenberg
Jeremy Rosenberg

Reputation: 25

Initializing and declaring a character array in C

This works.

char s[] = {'\x20', '\x09', '\x0a', '\x0d'};

These don't because "error: expected expression before ']' (or '}') token":

char s[4];
s = {'\x20', '\x09', '\x0a', '\x0d'};

char s[4];
s[]= {'\x20', '\x09', '\x0a', '\x0d'};

char s[4];
s[4]= {'\x20', '\x09', '\x0a', '\x0d'};

Is there any correct way to define and initialize on two different lines without using indices? I know I can say:

char s[4];
s[0] = '\x20';
s[1] = '\x09';
s[2] = '\x0a';
s[3] = '\x0d';

But out of curiosity, am I missing something trivial or is this unavoidable in C?

Upvotes: 1

Views: 194

Answers (3)

Huaxing Jin
Huaxing Jin

Reputation: 21

#include <string.h>

char s[5];
strcpy(s, "\x20\x09\x0a\x0d");

Upvotes: 1

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

you cannot assign like that without index after declaring.

So you can assign like that using the combination of strcpy and strcat.

For first one you can use strcpy, then strcat.

strcpy(s,"\x20");
strcat(s,"\x09");
strcat(s,"\x0a");
strcat(s,"\x0d");

Or else use the strcpy for copying the whole content in one time.

Upvotes: 0

Gopi
Gopi

Reputation: 19864

char s[] = {'\x20', '\x09', '\x0a', '\x0d'};

As you see the size of the array is not specified so you need to have initializer here and based on the initializer the size of the array is calculated and stored on stack.

Even if you have

char s[4];

s = {'1','2','3','4'};

This will not work because in C the standard says Arrays are not assignable

If you need to initialize then do it during declaring as already you are doing else fill in the array char by char or use inbuilt functions like strcpy()

Upvotes: 2

Related Questions