在哪里,当我创建这个数组的内存分配? (C) [英] Where is the memory allocated when I create this array? (C)
问题描述
比方说,我做这样的事情:
Let's say I do something like:
char* test[] = {"foo","bar","car"};
到底是什么这相当于,如果我做了很长的路?这是自动生成的内存,我将需要释放?我只是有点困惑。谢谢你。
What exactly is this equivalent to if I did it the long way? Is this automatically creating memory that I will need to free? I'm just sort of confused. Thanks.
推荐答案
测试
是指向char位于堆栈上的数组和字符串foo的
,栏
,有车族
存储在一个只读的位置。你需要释放什么。
test
is an array of pointers to char located on the stack, and the string literals "foo"
,"bar"
,"car"
are stored in a read only location. You need to free nothing.
试验[0]
,测试[1]
,测试[2]
点只读数据。请阅读有关作用域规则和变量的一生中C.默认情况下不具有一个块中存储类说明一个变量汽车
存储类说明,这意味着具有可变当地的寿命。
test[0]
, test[1]
, test[2]
point to read-only data. Please read about scoping rules and variable's lifetime in C. By default a variable which does not have storage-class specifier within a block has auto
storage-class specifier which means a variable with a local lifetime.
{
char* test[] = {"foo","bar","car"};
}
//cannot access test here
test [0] = "new"; // Compile time error - ‘test’ undeclared
在试图修改酒吧到焦油将给运行时错误:
While trying to modify "bar" to "tar" will give runtime error:
char* test[] = {"foo","bar","car"};
test[1][0] = "tar"; // Run-time error
不过,这是好的试验[0]
开始指向新
从富
:
test [0] ="new";
到foo的
丢失。
这篇关于在哪里,当我创建这个数组的内存分配? (C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!