第二次讲座盲点整理(指针与数组补充、左值与右值)

来源:互联网 发布:集金号软件 编辑:程序博客网 时间:2024/05/09 12:48

1、指针的类型

       32位环境下,执行下列程序,可以看出,无论是char型,int型,longint型,float型,还是double型,它们的指针大小都是4个字节。

#include <stdio.h>int main( int argc,char *agrv[] ){    printf("%d\n",sizeof(char *));    printf("%d\n",sizeof(int *));    printf("%d\n",sizeof(long *));    printf("%d\n",sizeof(float *));    printf("%d\n",sizeof(double *));    return 0;}

输出结果:

44444


         既然如此,那么为什么还要在定义一个指针的时候,还要声明其类型呢?指针是有类型的,但是这个类型不是给指针分配内存的,而是用来寻址的。

#include <stdio.h>int main( int argc,char *agrv[] ){    char *p = "abcdef";    printf("%p %p\n",p,p+1);    int a;    int *q =a ;    printf("%p %p\n",q,q+1);    return 0;}

输出结果:

0x8048508 0x80485090x8048479 0x804847d


         从运行结果可以看出,对指针进行+1操作,char型指针移动的大小是1*sizeof(char)=1,而int型指针移动大小则是1*sizeof(int)=4


2、左值与右值


         左值,代表一个内存地址值,并且通过这个内存地址值,就可以对该块内存进行读写(主要是写)操作。左值在编译时可知,表示存储结果的地方。

                 Anl-value says where to store the result.左值表明了将结果存储在何处。

         左值不但具有空间实体,还应具有读写访问权。Anl-value does not necessarily permit modification of the object itdesignates. For example, aconst object is anl-value that cannot be modified.(文本来自:http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc05lvalue.htm  里面有对左值和右值比较详细的解释)一个被const锁定了的变量就不可作为左值,它有空间,但是不可以被写入。

         在网上查询得知,之所以引入“modifiedl-value”这个概念,就是为了和数组名加以区分。如我们所知,数组名即数组的首地址,用来确定数组对象在内存中的位置,它是左值,但是它不能作为赋值的对象,因此,数组名是一个不可以被修改的左值。


         右值,也就是数据值,真实值。相对于左值而言,其含义是所代表的地址的内容。右值直到运行时才可知。

                 Theterm "r-value" is sometimes used to describe the value ofan expression and to distinguish it from an l-value. All l-values arer-values but not all r-values are l-values.

         “Alll-values are r-values but not all r-values arel-values.”——所有的左值同时也可作为右值,但不是所有的右值都可作为左值。

         在网上还找到一个这样的定义,不知道这个版本正确与否,不过从解释来看还蛮有道理:

                 L-value中的L指的是Location,表示可寻址。Avalue(computer science)that has an address.

                 R-value中的R指的是Read,表示可读。incomputer science, a value that does not have an address in a computerlanguage.






 
原创粉丝点击