分配一个值在C指针 [英] Allocating a value to a pointer in c

查看:152
本文介绍了分配一个值在C指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给一个值的指针。
这code正常工作

I am trying to give a value to a pointer. this code works fine

int i =5;   
int *ptr ;   
ptr = &i;   
printf(" %d\n",*ptr);   

但这种code显示错误

but this code shows an error

int i =5;   
int *ptr ;   
*ptr = 5;   
printf(" %d\n",*ptr);   

有人可以给我讲解一下?

can someone explain this to me?

推荐答案

在声明为int * PTR ,你会创建一个名为变量 PTR 可容纳的 INT 的地址。当你取消对它的引用在 * PTR = 5 ,你说专卖店5的地址 PTR 点 - 但作为 PTR 是未初始化的,它指向的是不确定的。所以你调用未定义的行为。

When you declare int *ptr, you're creating a variable called ptr which can hold the address of an int. When you dereference it in *ptr = 5, you're saying "store 5 in the address that ptr points to" - but as ptr is uninitialised, where it points to is undefined. So you're invoking undefined behaviour.

这是为int * 不存储在 INT ,但只是一个指向一个地址。目前仍然是一个真正的 INT 的该地址。

An int * does not store an int, but just an address that points to one. There still has to be a real int at that address.

如果你想分配一个 INT 本地范围之外的存在,你可以使用的malloc 。例如你一个简单的转换,而无需错误检查:

If you want to allocate an int that exists outside of the local scope, you can use malloc. A simple conversion of your example without error checking:

int *ptr = malloc(sizeof(int));
*ptr = 5;
printf(" %d\n",*ptr);

如果你使用的malloc ,只记得免费当您完成所分配的内存:

If you do use malloc, just remember to free the allocated memory when you're finished:

free(ptr);

这篇关于分配一个值在C指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆