Zaxter
Zaxter

Reputation: 3035

How is an empty string stored in a char array?

If I have an array declared as

char arr[1] = "";

What is actually stored in memory? What will a[0] be?

Upvotes: 1

Views: 4365

Answers (6)

sunrain
sunrain

Reputation: 1

C string is end with NULL, so the empty string "" actually is "\0", Compiler help do this, so strlen("") equal 0 but sizeof("") equal to 1.

Upvotes: 0

mahendiran.b
mahendiran.b

Reputation: 1323

It will pique more if the array is declared as char arr[] = "";

In this case the sizeof(arr) is 1 and strlen(arr) is 0 .

But still self analysis can be done by adding print like this printf("%d", arr[0]); So that you can understand by yourself.

string is a sequence of characters, in your case there is no character is present inside "". So it stores only '\0' character in arr[0].

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122493

Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e, '\0'.

char arr[1] = "";

is equivalent to:

char arr[1] = {'\0'};

You can imagine how it's stored in the memory from this.

Upvotes: 5

Keith Thompson
Keith Thompson

Reputation: 263567

a[0] is the null character, which can be referred to as '\0' or 0.

A string is, by definition, "a contiguous sequence of characters terminated by and including the first null character". For an empty string, the terminating null character is the first one (at index 0).

Upvotes: 2

Ishmeet
Ishmeet

Reputation: 1620

arr[0] = 0x00;

however, if you did not assign any value like

char arr[1];

then arr[0] = garbage value

Upvotes: 2

Amadan
Amadan

Reputation: 198446

C-strings are zero-terminated. Thus, "abc" is represented as { 'a', 'b', 'c', 0 }.

Empty strings thus just have the zero.

This is also the reason why a string must always be allocated to be one char larger than the maximum possible length.

Upvotes: 2

Related Questions