C/C++ 指针 数组 const 函数

用变量a给出下面的定义
a) 一个整型数(An integer)
b) 一个指向整型数的指针(A pointer to an integer)
c) 一个指向指针的的指针,它指向的指针是指向一个整型数(A pointer to a pointer toan integer)
d) 一个有10个整型数的数组(An array of 10integers)
e) 一个有10个指针的数组,该指针是指向一个整型数的(Anarray of 10 pointers to integers)
f) 一个指向有10个整型数数组的指针(A pointerto an array of 10 integers)
g) 一个指向函数的指针,该函数有一个整型参数并返回一个整型数(A pointer to a functionthat takes an integer as an argument and returns an integer)
h) 一个有10个指针的数组,该指针指向一个函数,该函数有一个整型参数并返回一个整型数( An array of ten pointers to functions that take an integer argumentand return an integer )

答案:
a) int a; // An integer
b) int *a; // A pointer to an integer
c) int **a; // A pointer to a pointer to an integer
d) int a[10]; // An array of 10 integers
e) int *a[10]; // An array of 10 pointers to integers
f) int (*a)[10]; // A pointer to an array of 10 integers
g) int (*a)(int); // A pointer to a function a that takes an integer argumentand returns an integer
h) int (*a[10])(int); // An array of 10 pointers to functions that take aninteger argument and return an integer

 

关于const指针 有如下一段小程序来解释.程序在VC6.0下编译通过.

// xxx.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

int main(int argc, char* argv[])
{
	int va =10;
	int vb = 32;
	int vc = 45;
	int vd = 67;

	const int * pa;
	int const * pb;
	int * const pc = &vc;
	int * pd;

	pa = &va;
	pb = &vb;
	pd = &vd;

	printf("va = %d\tvb=%d\tvc = %d\tvd=%d\n",va,vb,vc,vd);

	//编译不通过,报错如下:
	//xxx.cpp(28) : error C2166: l-value specifies const object
	//const * pa. pa指向的内容是不可修改的
	//(*pa) ++;

	//正确 相当于 expression=*pa,pa=pa+sizeof(*pa)
	*pa ++;

	//正确 相当于 expression=*pb,pb=pb+sizeof(*pb)
	*pb ++;

	//编译不通过,报错如下:
	//xxx.cpp(38) : error C2166: l-value specifies const object
	//*pc ++;

	//正确 *const pc . 仅表示pc指针本身不可修改,与所指向的目标无关
	(*pc)++;

	//编译不通过,报错如下:
	//xxx.cpp(46) : error C2166: l-value specifies const object
	//因为 *const pc. pc不可修改,此行试图修改pc
	//pc = pd;

	//指针的转换
	//把一个可以自由操作的指针赋值给一个功能受限的指针 
	//由于pa所能进行的操作在pd中都允许,所以赋值可以进行
	pa = pd;

	//编译不通过,报错如下:
	//xxx.cpp(56) : error C2440: '=' : cannot convert from 'const int *' to 'int *'
	//此行试图通过改用指针变量的方法来通过指针修改一个本来无法用指针修改的变量
	//pd = pa;

	//正确,相当于把一个常量赋值给一个变量,只是两个变量都是指针
	pd = pc;
	
	printf("pa = %d\t*pa=%d\n",pa,*pa);
	printf("pb = %d\t*pb=%d\n",pb,*pb);
	printf("pc = %d\t*pc=%d\n",pc,*pc);
	printf("pd = %d\t*pd=%d\n",pd,*pd);

	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值