函数 形参 使用 变量,由于是 传值调用,
所以,在函数体内,是不能够改变函数外部的变量的值的。
为了在函数内部修改,函数外部的变量的值,需要使用指针。
用指针的目的是,修改指针 指向的变量的值。
一维指针
一维指针作为形参的目的是 修改 指针指向的变量的值。
int funcA(int *a)
{
*a = 5;
}
int main(){
int a = 5 ;
int *ptr ;
ptr = &a ;
funcA(ptr);
}
二维指针
二维指针,也就是 指向指针变量的指针。
二维指针 作为形参,是为了可以在函数体内,修改二维指针指向的 指针变量的值。
被指向的指针变量
int funcB(char **pt){
(*pt) = (*pt) +1 ;
}
int main(){
char str[10] ={'a','b','c','d'} ;
char *ptr;
char **pt;
ptr = str
pt = &ptr ;
funcB(pt);
printf(“%c\n”,*ptr);
}
参考程序
/*--------------------------------------------------------------------------*/
/* Monitor */
/*----------------------------------------------*/
/* Get a value of the string */
/*----------------------------------------------*/
/* "123 -5 0x3ff 0b1111 0377 w "
^ 1st call returns 123 and next ptr
^ 2nd call returns -5 and next ptr
^ 3rd call returns 1023 and next ptr
^ 4th call returns 15 and next ptr
^ 5th call returns 255 and next ptr
^ 6th call fails and returns 0
*/
int xatoi ( /* 0:Failed, 1:Successful */
TCHAR **str, /* Pointer to pointer to the string */
long *res /* Pointer to a valiable to store the value */
)
{
unsigned long val;
unsigned char r, s = 0;
TCHAR c;
*res = 0;
while ((c = **str) == ' ') (*str)++; /* Skip leading spaces */
if (c == '-') { /* negative? */
s = 1;
c = *(++(*str));
}
if (c == '0') {
c = *(++(*str));
switch (c) {
case 'x': /* hexdecimal */
r = 16; c = *(++(*str));
break;
case 'b': /* binary */
r = 2; c = *(++(*str));
break;
default:
if (c <= ' ') return 1; /* single zero */
if (c < '0' || c > '9') return 0; /* invalid char */
r = 8; /* octal */
}
} else {
if (c < '0' || c > '9') return 0; /* EOL or invalid char */
r = 10; /* decimal */
}
val = 0;
while (c > ' ') {
if (c >= 'a') c -= 0x20;
c -= '0';
if (c >= 17) {
c -= 7;
if (c <= 9) return 0; /* invalid char */
}
if (c >= r) return 0; /* invalid char for current radix */
val = val * r + c;
c = *(++(*str));
}
if (s) val = 0 - val; /* apply sign if needed */
*res = val;
return 1;
}