您的位置:首页 > 其它

指针的各种形式

2015-08-19 14:34 357 查看
2013年中兴笔试题简答题第2小题,指针的多种形式。

2、请分别说出下面的A是什么?

(1) int (**A)[10] A是什么

A是一个指向 10个int类型元素数组的指针的指针。

(2)int *(*A)[10] A是什么?

A是一个指向 10个int *类型元素数组的指针。

(3)int (*A[10]) () A是什么?

A值指针数组,数组中每个指针指向一个输入参数为int、返回类型为int的函数。

下面分析指针各种形式的初步用法。

1、指针数组

int *a[2];

a是这个数组的数组名,数组中每个元素是int类型的指针。

#include<iostream>
using namespace std;
int main()
{
	int num1=10;
	int num2=11;
	int *A[2]={&num1,&num2};
	cout<<*A[0]<<endl;<span style="white-space:pre">		</span>					
	cout<<*A[1]<<endl;
}

数组下标[]结合性为自左向右,解除引用*的结合性自右向左。数组下标[]的优先级大于解除引用*的优先级。

上述程序定义了两个int类型变量num1,num2.把num1的地址和num2的地址用于指针数组A的初始化。

再调用A中指针来显示num1,num2的值。

#include<stdio.h>
int function1(int x){
    printf("function1,其中x的值为:%d\n",x);
    return x;
}
int function2(int x){
    printf("function2,其中x的值为:%d\n",x);
    return x;
}
int function3(int x){
    printf("function3,其中x的值为:%d\n",x);
    return x;
}
int main()
{
    int (*a[3]) (int);//a是一个指针数组,其中每一个指针是函数指针,
	//指向的函数的输入参数是int类型,返回值也是int类型
    a[0] = function1;//函数名也就是函数地址
    a[1] = function2;
    a[2] = function3;
    int x1 = a[0](1);
    int x2 = a[1](2);
    int x3 = a[2](3);
    printf("x1=%d\n",x1);
    printf("x2=%d\n",x2);
    printf("x3=%d\n",x3);
    return 0;
}



上述程序中int (*a[3])(int),定义了一个数组,这个数组中每个元素都是一个函数指针。



2、数组指针

数组指针本质上是一个指针,这个指针指向一定大小的数组。

#include<stdio.h>
int main()
{
int b[2][3] = {{1, 2, 3}, {4, 5, 6}};

int (*c)[3] = &b[0];//c是一个指针,它指向一个含有3个int类型元素的数组。
int(**a)[3];//a是指向一个有3个int类型元素的数组的指针的指针
a = &c;
printf("地址&b=%p\n",&b);
printf("地址&b+1=%p\n\n",&b+1);

printf("地址c=%p\n",c);
printf("地址c+1=%p\n",c+1);
printf("地址b=%p\n",b);
printf("地址b+1=%p\n",b+1);
printf("地址&b[0]=%p\n",&b[0]);
printf("地址&b[0]+1=%p\n\n",&b[0]+1);

printf("地址b[0]=%p\n",b[0]);
printf("地址b[0]+1=%p\n",b[0]+1);
printf("地址&b[0][0]=%p\n",&b[0][0]);
printf("地址&b[0][0]+1=%p\n\n",&b[0][0]+1);

printf("地址a=%p\n",a);
printf("地址a+1=%p\n\n",a+1);
return 0;
}


定义一个二维数组int b[2][3] = {{1, 2, 3}, {4, 5, 6}};



输出:



#include<iostream>
using namespace std;
int main()
{
	int * (*A)[3];//A为数组指针,数组中每个元素为int类型的指针。
	int num1=1;
	int num2=2;
	int num3=3;
	int * arr[3]={&num1,&num2,&num3};
	A=&arr;
	cout<<A<<endl;
	cout<<A+1<<endl;
	cout<<*(A[0][0])<<endl;
	cout<<*(A[0][1])<<endl;
	cout<<*(A[0][2])<<endl;
}
输出:



#include <iostream>
using namespace std;
void main() {

 int** array;
 array = new int* [2];
 int a[3] = {1, 2, 3};
 int b[4] = {4, 5, 6, 7};
 array[0] = a; // *array = a;
 array[1] = b; // *(array+1) = b;
 for(int i = 0; i < 3; i++)
	 cout << array[0][i]<<"\t";// cout << *(array[0] + i);
 cout << endl;
 for(int j = 0; j < 4; j++)
	 cout << array[1][j]<<"\t";// cout << *(array[1] + j);
}


输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: