找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 2182|回复: 1

Question4.2:What's wrong with this code?char *p;*p=malloc(10);

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-2 15:52:50 | 显示全部楼层 |阅读模式
Q: I'm trying to declare a pointer and allocate some space for it, but it's not working. What's wrong with this code? char *p;*p = malloc(10);
A: The pointer you declared is p, not *p. When you're manipulating the pointer itself (for example when you're setting it to make it point somewhere), you just use the name of the pointer:
               p = malloc(10);
It's when you're manipulating the pointed-to memory that you use * as an indirection operator:
               *p = 'H';
(It's easy to make the mistake shown in the question, though, because if you had used the malloc call as an initializer in the declaration of a local variable, it would have looked like this:
               char *p = malloc(10);
When you break an initialized pointer declaration up into a declaration and a later assignment, you have to remember to remove the *.)
In summary, in an expression, p is the pointer and *p is what it points to (a char, in this example).
See also questions 1.21, 7.1, 7.3c, and 8.3.     

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-2 16:14:05 | 显示全部楼层
问题:我试图去声明一个指针并且为其分配一些空间,但是没有作用。这个代码有什么问题:
       char *p;    *p=malloc(10);
回答:我们声明的指针是p,而不是*p。当你操作指针的时候(例如当你设置,让该指针指向某处的时候),你只要使用指针的名字就可以了:
       p=malloc(10);
当你操作指向某处内存的时候,使用*作为间接运算符:
       *p='H';
(尽管很容易犯问题中所描述的错误,因为如果你已经使用malloc调用来作为一个声明了的局部变量的初始化的时候,本来应该是这样的:
       char *p=malloc(10);
但是当你想将初始化一个声明的指针分开成一个指针声明和一个后面为其分配空间这种形式的时候,你要记住要将*移去。)
总之,在一个表达式里面,p是一个指针,而*p则是你想指向的东西(在这个例子里面是一个字符)。
参考问题1.21、7.1、7.3c和8.3。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-1 16:37 , Processed in 0.195661 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表