0

I know that when declaring char * s = "arbacadabra";, "abracadabra" refers to a const char *, but I cannot understand why when declaring t[] = "abracadabra", "abracadabra" is not interpreted as a const char* anymore, as long as it seems to be mutable.

    #include <stdio.h>

    int main(){
        char * s = "abracadabra";
        char t[] = "abracadabra";
        //s[0] = 'x';//produces an error
        t[0] = 'x';
    }
pauk
  • 350
  • 4
  • 15
  • 1
    `"abracadabra"` is not mutable in either case. In `t` you are allocating a new array and copying the characters from `"abracadabra"` into this array – M.M Feb 04 '21 at 22:18
  • Thus, "abracadabra" is another way to write {'a','b','r','a','c','a','d','a','b','r','a',NULL}, in the "t" case? – pauk Feb 04 '21 at 22:19
  • not really, as that syntax would not be accepted on the `s` line . It is an array of chars if that is what you are trying to say . – M.M Feb 04 '21 at 22:20
  • @pauk Yes in the 't' case (not NULL but `'\0'`) – xhienne Feb 04 '21 at 22:21
  • This is to your question in the comments: https://stackoverflow.com/questions/30533439/string-literals-vs-array-of-char-when-initializing-a-pointer – Eugene Sh. Feb 04 '21 at 22:23
  • My bad, it was '\0'. Also, why the compiler does not warn me somehow when I try to access and modify s[0]. I encounter a segmentation fault signal only after compiling the code. – pauk Feb 04 '21 at 22:23
  • Some systems allow writing via the `s` method and some don't. The former are not very common these days but the language was designed a long time ago . You can add `-Wwrite-strings` to your compile flags in gcc to get a diagnostic for this – M.M Feb 04 '21 at 22:25
  • Because it is not syntactically incorrect. But does invoke undefined behavior. C is very permissive. In a sense that it will let you shoot yourself in the foot. – Eugene Sh. Feb 04 '21 at 22:25
  • Indeed, but here the tricky thing is that a pointer to a constant should not let one change the value contained by it, as long as it is constant. It is something similar to attributing a new value to a macro. – pauk Feb 04 '21 at 22:28
  • 1
    @pauk You have never told the compiler this pointer is to something constant. How can it know? What if you reassign it with something "mutable"? – Eugene Sh. Feb 04 '21 at 22:30
  • 1
    `char * s = "abracadabra";` should be `const char * s = "abracadabra";` then the compiler will not allow *writing* to `s[N]`, but will allow *reading* from `s[N]`. – Remy Lebeau Feb 04 '21 at 22:31
  • Then, why I didn't get any compile error (or not even a warning) when performing char*s="abracadabra" without cast? – pauk Feb 04 '21 at 22:33
  • P.S.: I use CLion – pauk Feb 04 '21 at 22:34
  • Because the type of string literal is `char[]` and not `const char[]`. See here: https://stackoverflow.com/questions/2245664/what-is-the-type-of-string-literals-in-c-and-c – Eugene Sh. Feb 04 '21 at 22:38

0 Answers0