用const char指针分配的内存在哪里?

时间:2013-01-22 21:52:33

标签: c++ c memory

  

可能重复:
  Is a string literal in c++ created in static memory?
  C++ string literal data type storage

在此代码中:

const char * str = "hello world";

如果我理解正确,指针是4或8个字节,我想这将在堆栈上分配。 但分配和存储“hello world”的内存在哪里? 或者str指向的是什么?

3 个答案:

答案 0 :(得分:15)

没有分配。它通常存储在程序的代码段或堆栈中。这取决于编译器。无论哪种方式,它都指向以null结尾的字符数组。

答案 1 :(得分:6)

Essentailly,编译就像你写的那样:

const static char helloworld[12] 
             = {'h', 'e', 'l', 'l', 'o',' ','w', 'o', 'r', 'l', 'd', '\0'};

const char * str = helloworld;

通常将数组放在内存的某些只读部分中,可能位于可执行代码附近。

根据定义的位置,str将位于堆栈或全局内存空间中。

答案 2 :(得分:5)

C没有堆栈或堆。 C表示"hello world"是字符串文字,字符串文字具有静态存储持续时间

相关问题