一、指针
1、利用指针实现两数交换:
#include <iostream> using namespace std; void swap1(int p,int q){ int t; t=p; p=q; q=t; } void swap2(int *p,int *q){ int *t; *t=*p; *p=*q; *q=*t; } void swap3(int *p,int *q){ int *t; t=p; p=q; q=t; } void swap4(int *p,int *q){ int t; t=*p; *p=*q; *q=t; } void swap5(int &p,int &q){ int t; t=p; p=q; q=t; } int main(){ int a=1,b=2; swap4(&a,&b); swap5(a,b); cout<<a<<" "<<b; return 0; }
对于swap2:先是 int *t,声明一个int指针,但是没有地址,就直接*t=*p,将p地址的内容赋值给t地址,但是t没有地址,这在vs中是编译不通过的
对于swap3:虽然p地址的内容确实是a,但是p指针是个局部变量,swap3只是将p、q两个指针进行了交换,无法达到交换a,b的目的
2、指出以下程序的错误所在:
#include <iostream> using namespace std; void GetMemory(char *p,int num){ p=(char *)malloc(sizeof(char)*num); } int main(){ char *str=NULL; GetMemory(str,100); strcpy(str,"hello"); cout<<str; return 0; }
可以利用指向指针的指针方式修改此题:
#include <iostream> using namespace std; void GetMemory(char **p,int num){ *p=(char *)malloc(sizeof(char)*num); } int main(){ char *str=NULL; GetMemory(&str,100); strcpy(str,"hello"); cout<<str; return 0; }
#include <iostream> using namespace std; char * GetMemory(char *p,int num){ p=(char *)malloc(sizeof(char)*num); return p; } int main(){ char *str=NULL; str=GetMemory(str,100); strcpy(str,"hello"); cout<<str; return 0; }
#include <iostream> using namespace std; char * strA(){ char str[]="hello world"; return str; } int main(){ cout<<strA(); return 0; }
#include <iostream> using namespace std; char * strA(){ char *str="hello world"; return str; } int main(){ cout<<strA(); return 0; }
#include <iostream> using namespace std; char * strA(){ static char str[]="hello world"; return str; } int main(){ cout<<strA(); return 0; }
#include <iostream> using namespace std; struct S{ int i; int *p; }; int main(){ S s; int *p=&s.i; p[0]=4; p[1]=3; s.p=p; s.p[1]=1; s.p[0]=2; //cout<<s.p; return 0; }
p指针指向s.i的地址,p[0]=4,p[1]=3,所以此时s.i为4,s.p为3(地址为3)
s.p=p,即s.p=&s.i,s.p[1]也就是s.p,是同一个地方,此时s.p地址为1
最后,s.p[0],因为s.p地址变了,所以就不是s.i了,相当于*((int *)1)=2;访问的是0x00000001的空间——对一个未做声明的地址进行访问,访问出错
二、函数指针
1、写出函数指针、函数返回指针、const指针、指向const指针、指向const的const指针
void (*f)() void * f() const int* int * const const int* const
float(**def)[10];//def是一个二级指针,它指向的是一个一维数组的指针,数组元素都是float double*(*gh)[10];//gh是一个指针,它指向一个一维数组,数组元素都是double* double(*f[10])();//f是一个数组,有10个元素,元素都是函数的指针,指向的函数类型是没有参数且返回double的函数 int*((*b)[10]);//就跟int*(*b)[10]是一样的,是一维数组的指针 long(*fun)(int);//函数指针,参数int返回值long int(*(*f)(int,int))(int);//f是一个函数的指针,指向的函数类型是两个int参数且返回一个函数指针的函数,返回的函数指针指向一个有一个int参数且返回int的函数
原文:http://blog.csdn.net/starcuan/article/details/19978821