我只是不明白这个指针的情况[关闭]

问题描述 投票:0回答:2

这是我的代码:

int *p;
p = 4;
printf("p is %p\n", p);
free(p);
// Need p=NULL, but I don't
int *q;
q = 5:
printf("q is %i", *q);

然后错误就来了。 我只需要一个解释。

c pointers
2个回答
3
投票
int *p;

是一个指向 int 的指针。

p = 4;

使其指向地址

0x4

free(p);

尝试释放地址0x4

基本上,您正在尝试释放无法释放的资源。

int *q;
q = 5;

将 q 指向地址`0x5;

*q;

0x5
地址读取,这很可能会崩溃。 (这个地址也没有对齐)。

指针不是整数...您编写的程序表明缺乏对指针是什么以及为什么/如何使用它们的理解。


0
投票
Int *p; // You had better use int* p = NULL; we don't like wild pointers
//p = new int;
p=4; // I guess you want put the value of 4 to a variable, so *p = 4;
printf("p is %p\n",p);//    printf("p is %d\n",*p);
free(p);//just correct in theory, no one can tell what happens in reality.
/* 
if ( NULL != p )
{
    delete p;
    p = NULL;
}
*/
© www.soinside.com 2019 - 2024. All rights reserved.