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

 #include <iostream>
#include <string.h>
using namespace std; int main()
{
//difference 1: 指向是否可以更改
//数组内容可变,但是不可以++
char d1a[] = "hello";
d1a[] = '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[];
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:
the size of b is:
上一篇:MooseFS分布式文件系统介绍及安装教程详解


下一篇:jdbc mysql 取数,突然取不到数据,数据库中有数据