D
D
dandropov952018-08-28 17:34:35
C++ / C#
dandropov95, 2018-08-28 17:34:35

Why can you change a constant character array in C?

Why is this allowed in C?

const char string[] = "Hello world";
char * ptr = strchr(string, 'H');

puts(string); // Hello world

// string[0] = 'h'; // error
*ptr = 'h';
    
puts(string); // hello world

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-08-28
@jcmvbkbc

Why is this allowed in C?

What you have written is qualified by the standard as Undefined behavior (c99 6.7.3:5):
If an attempt is made to modify an object defined with a const-qualified type through use
of an lvalue with non-const-qualified type, the behavior is undefined.

Why it's technically possible to do this and this code works -- because the string array has an automatic lifetime and the compiler pushes it onto the stack. Those. memory is not actually constant.
Why does the strchr function take const char *but return char *? To show that she herself does not change her argument, but not to force all her users to cast the result. I would say that this function is the problem, but it is so old that no one will fix its prototype.
In C++, one could solve this problem by providing two overloads of strchr -- char *strchr(char *, char)and const char *strchr(const char *, char), but there is no function overloading in C.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question