Par*_*ius 1 c++ malloc stack pointers reference
如何在运行时区分指针和引用?例如,如果我想释放数据类型的指针而不知道它是否是指针,我该怎么做?是否有任何方法可以判断是否已在堆栈上或通过malloc()分配变量?
void destInt(int* var)
{
free(var);
}
int num = 3;
int &numRef = num;
int* numPtr = (int*)malloc(sizeof(int));
*numPtr = num;
destInt(&numRef); //Syntactically correct but generates invalid pointer()
destInt(numPtr); //Fine syntactically and logically
Run Code Online (Sandbox Code Playgroud)
不,不是在一般情况下,不是以便携式方式.如果你知道堆的内存在哪里,你可以做出有根据的猜测,但不能以任何可靠的方式.
编辑:还要注意C没有引用.C中的&运算符用于获取变量的地址.