`

c中的指针

阅读更多
1.指针与++操作
#include <stdio.h>

int  main(){
	int a[] = {1,11,111,1111};
	int *p = &a[0], *p1 = &a[2];

	printf("p=%d\n",*++p);
	printf("p1=%d\n",*p1++);
	printf("p1=%d\n",*p1);

	int temp = ++(*p);
	temp = (*p)++;
	int temp1 = *p;
	printf("temp=%d\n",temp);
	printf("temp1=%d\n",temp1);
}


结果:
p=11
p1=111
p1=1111
temp=12
temp1=13


2.数组指针(用来表示数组的指针。一维数组比较简单,这里以二维数组为例)
#include<stdio.h>

int main(){
	int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
	int (*p)[4] = a;//表示每个指针长度为 int[4]的指针

	int i,j,sum = 0;
	for(i=0;i<3;i++){
		for(j=0;j<4;j++){
			sum += *(*(p+i)+j);
		}
	}
	printf("sum is:%d\n",sum);
}


结果:
sum is:78

3.指针数组(用来存储指针的数组)
#include<stdio.h>

int main(){
	int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
	int *p[3];//表示长度为3的数组,数组元素是指针
	int i,j,sum=0;
	for(i=0;i<3;i++){
		p[i] = a[i];
	}

	for(i=0;i<3;i++){
		for(j=0;j<4;j++){
			sum += *(p[i] + j);
		}
	}
	printf("sum is:%d\n",sum);
}


结果:
sum is:78

4.指针的指针(多级指针)
#include<stdio.h>

int main(){
	int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
	int *q[3] = {a[0],a[1],a[2]};
	int **p = &q[0];//指针的指针,*p指向的都是指针。

	int i,j,sum = 0;
	for(i=0;i<3;i++){
		for(j=0;j<4;j++){
			sum += *(*(p+i)+j);
		}
	}
	printf("sum is:%d\n",sum);
}


结果:
sum is:78

5. 函数指针
函数指针的声明形式如: 数据类型 (*函数指针名)()
#include<stdio.h>
#include<string.h>

void check(char *, char *, int (*p)());

int main(){
	char *a = "hello", *b = "hello", *c = "world";
	int (*cmp)() = strcmp;
	check(a,b,cmp);
	check(a,c,cmp);
}

void check(char *a, char *b, int (*cmp)()){
	if(!cmp(a,b)){
		printf("%s equals %s\n",a,b);
	}else{
		printf("%s does not equal %s\n",a,b);
	}
}


结果:
hello equals hello
hello does not equal world

6. const和指针的混合使用
  • const 数据类型符 *指针变量名(指向的内容是常量)
  • int a=10, b=10;
    const int *pa = &a;
    pa = &b;//可以
    *pa = b;//不可以
  • 数据类型符 *const 指针变量名(指针是常量)
  • int a=10, b=10;
    int *const pa = &a;
    pa = &b;//不可以
    *pa = b;//可以
  • const 数据类型符 *const 指针变量名(指针和指向的内容都是常量)
  • int a=10, b=10;
    const int *const pa = &a;
    pa = &b;//不可以
    *pa = b;//不可以
    分享到:
    评论

    相关推荐

    Global site tag (gtag.js) - Google Analytics