How C strings are allocated in memory?

前端 未结 5 1603
情话喂你
情话喂你 2020-12-01 14:36

Say I have a simple function that returns a C string this way:

const char * getString()
{
  const char * ptr = \"blah blah\";
  return ptr; 
}
5条回答
  •  长情又很酷
    2020-12-01 15:31

    You are right in that they are not the same thing. char a[] is an array formed on the stack, and then filled with "blah.." - inside the function, you have essentially `const char a[15]; strcpy(a, "blah blah blah");"

    The const char *ptr = "blah blah blah"; on the other hand is simply a pointer (the pointer itself is on the stack), and the pointer points to the string "blah blah blah", which is stored somewhere else [in "read only data" most likely].

    You will notice a big difference if you try to alter something, e.g: a[2] = 'e'; vs ptr[2] = 'e'; - the first one will succeed, because you are modifying a stack value, where the second (probably) will fail, because you are modifying a read only piece of memory, which of course should not work.

提交回复
热议问题