C-指针和数组的区别

指针的操做:ios

   容许:1)同类型指针的赋值数组

     2)与整形的加减运算函数

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

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

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

       2)与float,double类型相加blog

       3)不经过类型转换,直接赋予除void*以外的其它类型指针内存

指针与数组的相同点:string

  1,a[i]能够用*(a+i)表示io

  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
相关文章
相关标签/搜索