指针和数组

指针和数组

指针和数组在C语言中有错综复杂的联系。在前面的课程中,你学会了如何声明数组变量:

int anArray[5]; // declare array of 5 integers
anArray is actually a pointer that points to the first element of the array! Because the array variable is a pointer, you can dereference it, which returns array element 0:

int anArray[5] = { 9, 7, 5, 3, 1 };

// dereferencing an array returns the first element (element 0)
cout << *anArray; // prints 9!

char szName[] = "Jason"; // C-style string (also an array)
cout << *szName; // prints 'J'

指针的算术运算

C语言允许你在指针执行整数的加减运算。如果pnptr指向一个整数,pnptr + 1 pnptr后在内存中的地址的下一个整数。pnptr - 1是在pnptr以前的整数地址。

请注意,pnptr + 1不在pnptr返回地址,但下一个对象,pnptr分型。如果pnptr指向一个整数(假设4字节),pnptr + 3意味着在pnptr 3个整数,这是12个地址后pnptr。如果pnptr指向一个char,这始终是1字节,pnptr + 3意味着在pnptr 3字符,这是3个地址后pnptr。

计算一个指针的算术表达式的结果时,编译器总是乘以整数操作数所指对象的大小。这就是所谓的缩放。

下面的程序:

1
2
3
4
5
6
7
int nValue = 7;
int *pnPtr = &nValue;
 
cout << pnPtr << endl;
cout << pnPtr+1 << endl;
cout << pnPtr+2 << endl;
cout << pnPtr+3 << endl;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值