static const int MAX_SIZE = 256; //I assume this is static Data
bool initialiseArray(int* arrayParam, int sizeParam) //where does this lie?
{
if(size > MAX_SIZE)
{
return false;
}
for(int i=0; i<sizeParam; i++)
{
arrayParam[i] = 9;
}
return true;
}
void main()
{
int* myArray = new int[30]; //I assume this is allocated on heap memory
bool res = initialiseArray(myArray, 30); //Where does this lie?
delete myArray;
}
我们目前正在学习不同类别的内存,我知道有 -代码内存 -静态数据 -运行时堆栈 -自由存储(堆)
我已经评论了我不确定的地方,只是想知道是否有人可以帮助我。我对运行时堆栈的定义描述了它用于函数,但我的代码内存定义它包含方法/函数的所有指令,所以我有点困惑。
谁能伸出援手?
最佳答案
static const int MAX_SIZE = 256; //I assume this is static Data
的确如此。事实上,因为它是 const
,这个值可能根本不会保留在您的最终可执行文件中,因为编译器可以在它看到 MAX_SIZE
的任何地方替换“256” .
bool initialiseArray(int* arrayParam, int sizeParam) //where does this lie?
initialiseArray()
的代码函数将在您的可执行文件的数据部分中。您可以获得指向内存地址的指针,并通过该地址调用该函数,但除此之外,您无能为力。
arrayParam
和 sizeParam
参数将在堆栈上按值传递给函数。同样,bool
返回值将被放入调用函数的堆栈区。
int* myArray = new int[30]; //I assume this is allocated on heap memory
正确。
bool res = initialiseArray(myArray, 30); //Where does this lie?
实际上,myArray
指针和文字 30
被复制到initialiseArray()
的栈区,然后对它们进行操作,然后是结果 bool
被复制到调用函数的栈区。
参数传递的实际细节要复杂得多,并且取决于调用约定(其中有几个,特别是在 Windows 上),但除非你正在做一些非常专业的事情,否则它们并不重要 :-)
关于c++ - 不同类别的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542489/