当我测试双指针行为时,我得到了一个我不太理解的结果。
==>代码1:
int main (int argc , char **argv)
{
if(*argv+1 ==NULL)
{
printf("NULL pointer \n");
exit(0) ;
}
else
{
printf("test double pointer[] : %s \n ",*argv+1);
}
return(0);
}
====> 结果 1
root@root:/home/aa/test# ./geip 1255
test double pointer[] : /geip
root@root:/home/aa/test#
===>代码2:
int main (int argc , char **argv)
{
if(*argv+9 ==NULL)
{
printf("NULL pointer \n");
exit(0) ;
}
else
{
printf("test double pointer[] : %s \n ",*argv+9);
}
return(0);
}
==> 结果 2:
root@root:/home/aa/test# ./geip 1255
test double pointer[] : 55
root@root:/home/aa/test#
==> 结果 3:
root@root:/home/aa/test# ./geip
test double pointer[] : ELL=/bin/bash
root@root:/home/aa/test#
似乎 printf 从第 n 个单词(1 和 9)开始显示 我们如何解释指针的这种行为?
最佳答案
你用错了。
*argv+1
将被解释为 (argv[0])+1
并且因为 argv[0]
是“./geip"你得到 "/geip"。
*argv+9
将被解释为 (argv[0])+9
但是因为 argv[0]
只有长度 6结果未定义。
在您的情况下,argv 可能存储为:
. / g e i p \0 1 2 5 5 \0
0 1 2 3 4 5 6 7 8 9 10 11
这解释了为什么 +9
让你得到“55”
但你真的应该忘记它,因为它永远不会有用!这是未定义的行为,永远不应该使用。
关于c - 指针的行为;字符 ** argv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17617168/