C-指针和数组的区别

指针的操作:

   允许:1)同类型指针的赋值

     2)与整形的加减运算

     3)指向同一数组内指针的减运算和比较

     4)赋 ‘0’ 或与 ‘0’ 比较

   不允许:1)两指针的相加,相乘除,位移或mask

       2)与float,double类型相加

       3)不通过类型转换,直接赋予除void*之外的其它类型指针

指针与数组的相同点:

  1,a[i]可以用*(a+i)表示

  2, 当传递给函数作为实参时,则都是一个地址

指针和数组的区别:

  1,数组是一块连续区域,要么是在静态存储区被创建(如全局数组),要么是在栈上被创建,可以更改指向。数组名对应着(而不是指向)一块内存,其地址与容量在生命期内保持不变,不能更改指向。指针是一个变量,可以++;数组不是一个变量,不可以++

  2,sizeof指针表示指针大小,一般为4byte;sizeof数组表示数组占内存大小。

  3,数组不可以直接赋值与比较,如果是字符数组要用strcpy和stycmp。指针可以直接赋值,但是赋过去的是地址。比较一般也不比较地址,一般比较内容。

 

 1 #include <iostream>
 2 #include <string.h>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     //difference 1: 指向是否可以更改
 8     //数组内容可变,但是不可以++
 9     char d1a[] = "hello";
10     d1a[2] = 'L';
11     //d1a++;
12     cout << d1a << endl;
13     //指针指向内容可变,也可以++
14     char* d1p = "world";
15     //d1p[2] = 'R';
16     cout << " " << d1p << endl;
17     //output the address of point to char
18     cout << "the address of d1p is: " 
19         << static_cast<void*>(d1p) << endl;
20     d1p++;
21     cout << "after ++, the address of d1p is: " 
22         << static_cast<void*>(d1p) << endl;
23 
24     //difference 2: copy and compare
25     //ARRAY, 不能使用赋值或者比较
26     char a[] = "hello";
27     char b[10];
28     strcpy(b, a); //can't use b = a;
29     //POINTER, valid
30     char* pa = "world";
31     char* pb;
32     pb = pa;
33 
34     //difference 3: sizeof
35     cout << "the size of a is: " << sizeof(a) << endl;
36     cout << "the size of b is: " << sizeof(pa) << endl;
37         
38 }

 输出:

$ ./a.exe
heLlo
 world
the address of d1p is: 0x445006
after ++, the address of d1p is: 0x445007
the size of a is: 6
the size of b is: 4

 

 

posted on 2014-06-26 13:21  醉清风JM  阅读(318)  评论(0)    收藏  举报

导航