您的位置:首页 > 其它

C-指针和数组的区别

2014-06-26 13:21 162 查看
指针的操作:

  允许: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。指针可以直接赋值,但是赋过去的是地址。比较一般也不比较地址,一般比较内容。

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
//difference 1: 指向是否可以更改
//数组内容可变,但是不可以++
char d1a[] = "hello";
d1a[2] = 'L';
//d1a++;
cout << d1a << endl;
//指针指向内容可变,也可以++
char* d1p = "world";
//d1p[2] = 'R';
cout << " " << d1p << endl;
//output the address of point to char
cout << "the address of d1p is: "
<< static_cast<void*>(d1p) << endl;
d1p++;
cout << "after ++, the address of d1p is: "
<< static_cast<void*>(d1p) << endl;

//difference 2: copy and compare
//ARRAY, 不能使用赋值或者比较
char a[] = "hello";
char b[10];
strcpy(b, a); //can't use b = a;
//POINTER, valid
char* pa = "world";
char* pb;
pb = pa;

//difference 3: sizeof
cout << "the size of a is: " << sizeof(a) << endl;
cout << "the size of b is: " << sizeof(pa) << endl;

}


输出:

$ ./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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: