Published on

Initializing a character with an empty value in C

Authors
  • avatar
    Name
    hwahyeon
    Twitter

In Python, it's possible to initialize a string as an empty string:

string = ""

However, in C, an expression like string[0] = '' is incorrect because C does not allow empty characters (''). While you can use a space character (' '), it represents a space, not an empty value.

char string[10];
string[0] = ''
// error: empty character constant

Strings in C are represented as char arrays, and they must always include a null character (\0) to signify the end of the string.

To set a specific position in the string to a null character in C, you can do the following:

char string[100];  // Declare the size of the string
string[0] = '\0';  // Set the first character to null

This effectively treats the string array as an empty string, as the first element is now a null character.

Since Python strings are immutable, you cannot modify individual characters directly using something like string[0] = '1'. If you want to modify part of a string, you need to reassign the entire string.