0
int main() {

        char* string = "Hello world";
        string[2] = 'd';

        printf("%s\n", string);

        return 0;
}
int main() {

        time_t now;
        time(&now);
                                                                                            $        
        char* time = ctime(&now) + 11;
        time[8] = '\0';                                                                      
        printf("%s\n", time);

        return 0;
}

Like in the second example I am able to modify a particular index of the array for the pointer to terminate the string with the NULL character. However, with the first one I just try to change the character at index 2 to the letter 'd' but it refuses to print the output and I a Segmentation fault error!

My guess is that in the second one there is some very slight difference where the ampersand is used to get the contents of the address in memory to where the pointer points to but that's just my guess. Would love if someone could give me a clear and not overly confusing explanation as to why this is... Thanks!

radhadman
  • 19
  • 2
  • 2
    `char* string = "Hello world";` is wrong. Hardcoded strings are not writable so you cannot change them. The correct code is `char string[] = "Hello world";` – Jerry Jeremiah Sep 28 '20 at 22:25
  • 1
    When using pointers to literal strings, make it a habit to *always* use `const char *`. IMO the committee behind the C specification should really step up and make literal strings proper constant arrays and require `const char *` (as is done for C++). – Some programmer dude Sep 28 '20 at 22:28
  • 2
    The time conversion functions are documented in C 2018 7.27.3 to return a pointer to a static array of `char`. Such an array can be modified. In particular, the documentation of `asctime`, referred to from `ctime`, specifies it uses the equivalent of code that provides a static object with no restriction on modifying it. In contrast, setting the value of `string` with a string literal results in pointing to data that it might not be possible to modify, as 6.4.5 7 says that the behavior upon attempting to modify the data of a string literal is not defined. – Eric Postpischil Sep 28 '20 at 22:32
  • 1
    @Amessihel: This is not a proper duplicate because the purported original does not assert, explain, or document that `ctime` provides a pointer to a static array without restrictions on modifying it. – Eric Postpischil Sep 28 '20 at 22:33

0 Answers0