0

Why the statement below is correct even though the type of the string is const char *? As far as I know, the array must be const since I'm trying to type cast from const to non-const object but compilers accept that statement.

char s[] = "test";

1
  • 1
    In this context "test" is a literal string used as an initializer for the char array. The literal string is read-only, but the array where it gets copied during initialization does not have to be read-only. Commented Dec 27, 2020 at 22:25

1 Answer 1

1

This is actually just a special syntax for initializing an array: https://en.cppreference.com/w/c/language/array_initialization

You can initialize a char array using a string literal, which is simply equivalent to declaring an array containing each of the characters in the string (including the null terminator).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.