实例一:
//此程序主要是从字符串中截取一个新的字符串。
//目的主要理解一级指针与二级指针的处理方法。
#include
char *strchr(const char *p,int ch)
{
for(;; ++p)
{
if(*p == ch)
return((char *)p);
if(!*p)
return((char *)NULL);
}
}
int at_tok_nextstr(char **p_cur,char ch)
{
if(*p_cur==NULL)
return -1;
*p_cur = strchr(*p_cur,ch);
if(*p_cur == NULL)
return -1;
(*p_cur)++;
return 0;
}
char * Getnewaddr(char *p_cur,char ch)
{
for(;*p_cur!=ch;)
{
p_cur++;
}
p_cur++;
return p_cur;
}
void main()
{
char *line = "+COPS: oh my god!";
char *response = "+COPS: oh my god!";
char *p_res=NULL;
int err;
//使用二级指针处理,line的指针已经改变
err=at_tok_nextstr(&line,':');
if(err < 0)
goto error;
printf("line value:%s\n",line);
//从函数中返回一个一级指针 ,response指针未变
p_res = Getnewaddr(response,':');
printf("response value:%s\n",response);
printf("p_res value:%s\n",p_res);
return;
error:
printf("error\n");
}
输出结果:
line value: oh my god!
response value:+COPS: oh my god!
p_res value: oh my god!
实例二:
字符串排序(摘自谭浩强C语言设计)
#include
int mystrcmp(char *str1,char *str2)
{
while((*str1 != '\0') && (*str2 != '\0'))
{
if(*str1 > *str2)
return 1;
else if(*str1 < *str2)
return -1;
else
{
str1++;
str2++;
}
}
return 0;
}
void sortup(char **pt,int n)
{
int i,j;
char *tmp;
for(i=0;i {
for(j=i+1;j {
if(mystrcmp(*(pt+i),*(pt+j)) > 0)
{
tmp = *(pt+i);
*(pt+i) = *(pt+j);
*(pt+j) = tmp;
}
}
}
}
void print(char **p,char n)
{
int i;
for(i = 0;i < n;i++)
{
printf("%s \n",*p++);
}
}
void main()
{
char *name = "\"Follow me\",\"BASIC\",\"Great Wall\",\"FORTRAIN\",\"Computer design\"";
char **p;
p = &name;
printf("%x %x %s\n",*p);
}
实例三
#include
void swap1(int *p1,int *p2)
{
int tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void swap2(int *p1,int *p2)
{
int *tmp;
tmp = p1;
p1 = p2;
p2 = tmp;
}
void swap3(int **p1,int **p2)
{
int *tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void main()
{
int a = 10;
int b = 20;
int *pa = &a;
int *pb = &b;
swap1(pa,pb);
printf("After swap1:\n");
printf("a = %d,b = %d *pa = %d,*pb = %d \n",a,b,*pa,*pb);
printf("add_a = %x,b = %x,pa = %x,pb = %x \n",&a,&b,pa,pb);
a = 10;
b = 20;
pa = &a;
pb = &b;
swap2(pa,pb);
printf("After swap2:\n");
printf("a = %d,b = %d *pa = %d,*pb = %d \n",a,b,*pa,*pb);
printf("add_a = %x,b = %x,pa = %x,pb = %x \n",&a,&b,pa,pb);
a = 10;
b = 20;
pa = &a;
pb = &b;
swap3(&pa,&pb);
printf("After swap3:\n");
printf("a = %d,b = %d *pa = %d,*pb = %d \n",a,b,*pa,*pb);
printf("add_a = %x,b = %x,pa = %x,pb = %x \n",&a,&b,pa,pb);
}
实验现象:
After swap1:
a = 20,b = 10 *pa = 20,*pb = 10
add_a = bfe948dc,b = bfe948d8,pa = bfe948dc,pb = bfe948d8
After swap2:
a = 10,b = 20 *pa = 10,*pb = 20
add_a = bfe948dc,b = bfe948d8,pa = bfe948dc,pb = bfe948d8
After swap3:
a = 10,b = 20 *pa = 20,*pb = 10
add_a = bfe948dc,b = bfe948d8,pa = bfe948d8,pb = bfe948dc
总结:C语言实参变量之间的数据传递时单向的“值传递”方式。指针变量作函数参数也要遵循这一规则。不可能
通过函数来改变实参指针变量的值,但可以改变实参指针变量所指变量的值。
阅读(3720) | 评论(0) | 转发(0) |