How C strings are allocated in memory?

前端 未结 5 1607
情话喂你
情话喂你 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条回答
  •  旧时难觅i
    2020-12-01 15:37

    In your function, the scope of a[] array is within the function getString2(). its local array variable.

    const char *getString2()
    {
      const char a[] = "blah blah blah";
      return a;
    }  
    

    In above case string "blah blah blah" copies fist into a[] and your are trying to return that array with return a statement, but not constant string.

    Where as in first code getString() : ptr = "blah blah"; ptr point to memory that has global scope.

    const char * getString()
    {
      const char * ptr = "blah blah";
      return ptr; 
    }
    

    In this case you returns the address of constant string "blah blah" that is legal to do.

    So actually its Scope problem.

    it helpful to learn about Memory Layout of C Programs and Variable Scope in C.

提交回复
热议问题