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

Question1.5 What's wrong with this declaration? e.g.:char* p1,p2

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-6-27 16:08:10 | 显示全部楼层 |阅读模式
Nothing is wrong with the declaration--except that it doesn't do what you probably want. The * in a pointer declaration is not part of the base type; it is part of the declarator containing the name being declared (see question 1.21). That is, in C, the syntax and interpretation of a declaration is not really     type identifier ;but rather base_type thing_that_gives_base_type ;where ``thing_that_gives_base_type''--the declarator--is either a simple identifier, or a notation like *p or a[10] or f() indicating that the variable being declared is a pointer to, array of, or function returning that base_type. (Of course, more complicated declarators are possible as well.)
In the declaration as written in the question, no matter what the whitespace suggests, the base type is char and the first declarator is ``* p1'', and since the declarator contains a *, it declares p1 as a pointer-to-char. The declarator for p2, however, contains nothing but p2, so p2 is declared as a plain char, probably not what was intended. To declare two pointers within the same declaration, use char *p1, *p2;Since the * is part of the declarator, it's best to use whitespace as shown; writing char* invites mistakes and confusion.
See also question 1.13.
Additional links: Bjarne Stroustrup's opinion

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-6-27 17:28:37 | 显示全部楼层
问题:对于这样的声明char* p1,p2;有什么问题?当我试图想要指针变量p2的时候我却得到了错误的结果。
回答:这样的声明没有错误,只是它不会得到你想要的结果。指针变量的声明中的*号不是作为基本类型的一部分的;它是包含在要声明的名字中的说明符的一个部分(参考问题1.21)。在C语言中,一个声明的语法和解释实际上不是
          type indentifier;(类型 标识符)
而是
          base_type thing_that_gives_base_type;(基本类型 跟着基本类型的一些说明符)
对于"thing_that_gives_base_type"这样的一个说明符要么是一个简单的标识符,要么是像*p或者a[10]或者f()这样的符号,他们分别表示的是声明一个char型的指针变量、声明一个数组或者是声明一个返回基本类型变量的函数(当然更复杂的说明符也是一样的)。
    正如在问题中描述的声明,无论空白的地方想要暗示什么(char*后面是空白部分),我们应该知道基本类型就是char,第一个说明符是"*p1",由于在说明符中包含了一个*号,它表明了p1是指向char类型的指针变量。至于说明符p2,它除了p2就不再包含其他的信息,因此p2仅仅只是一个char型的变量,并不是我们所想的是一个指针变量。想要在一个声明中表示两个指针变量,应该使用char *p1,*p2;
        由于*号是说明符中的一部分,那么按照刚才所描述的使用空格是最好的(写成char *);而如果写成问题中的char*反而会招致一些错误和迷惑。
参考问题1.13。

14

主题

65

回帖

0

积分

新手上路

积分
0
发表于 2013-6-28 01:12:16 | 显示全部楼层
以前也被这种写法骗到过,以为p2是指针类型。后面在定义指针变量时让*挨着变量写,再到后来一行只定义一个变量,这个问题也就不存在了。呵呵

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-6-28 10:23:16 | 显示全部楼层
嗯,这也是一个避免上述问题的方法啊。。。

205

主题

173

回帖

6925

积分

论坛元老

积分
6925
发表于 2013-6-28 10:24:04 | 显示全部楼层
题目应该是这样吧?:What's wrong with this declaration? e.g.:char* p1,p2

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-6-28 10:26:28 | 显示全部楼层
恩恩,当时写前面的问题的时候由于字符限制,所以我后面的都只写前面一句了,我再加上去。。。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

GMT+8, 2026-2-1 12:32 , Processed in 0.081062 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

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