Opa*_*pal 6 c reverse pointers dereference
我有一些关于反转空终止C字符串的概念性问题,以及关于指针性质的澄清问题.
输入可能是
char arr[] = "opal";
Run Code Online (Sandbox Code Playgroud)
和代码:
void reverse(char *str) { /* does *str = opal or does *str = o since the pointer str is type char? */
char* end = str; /* what is the difference between char* end and char *end? and is *end pointing to opal now? */
char tmp;
if (str) { /* if str isn't null? */
while (*end)
++end;
}
--end; /* end pointer points to l now */
while (str < end) { /* why not *str < *end? is this asking while o < l? */
tmp = *str; /* tmp = o */
*str++ = *end; /* what is the difference between *str++ and ++str? does *str++ = l? */
*end-- = tmp; /* *end points to o */
}
}
}
Run Code Online (Sandbox Code Playgroud)
很多问题......试图捕捉每个问题的答案:
/*做*str = opal或者*str = o,因为指针str是char类型?*/
*str是'o'因为它指向的第一个字符
/*char*end和char*end之间有什么区别?现在是*结束指向蛋白石?*/
char *end和之间没有区别char* end.写作时会变得更加棘手
char* a, b;
Run Code Online (Sandbox Code Playgroud)
因为这相当于
char *a, b;
Run Code Online (Sandbox Code Playgroud)
而不是,你可能会想到
char *a, *b;
Run Code Online (Sandbox Code Playgroud)
这就是写作更清晰的原因char *end;.
并end指出opal现在 - *end是'o'.
if(str){/*如果str不为空?*/
是的 - 测试你没有传递一个NULL指针
为了测试你没有传递一个长度为0的字符串,你必须测试*str(在测试之后str不是NULL,否则你会因为"敢于看*NULL"而得到分段错误)
while(str <end){/*为什么不*str <*end?这是在o <l?*/
测试指针 - 一个是向末端移动,另一个向后移动.当你在中间相遇时,你会停下来; 否则你做两次交换,并且没有净效应......
Run Code Online (Sandbox Code Playgroud)*str++ = *end; /* what is the difference between *str++ and ++str? does *str++ = l? */
首先复制*endto 的值*str,然后递增str指针.如果你放++str,你先增加,然后使用它.这意味着你l代替了p而不是代替o.
编辑一个关于你的代码的批评(超出你提出的问题,并回应@chux的评论):当你测试if(str){}你真的需要一个else return;声明,因为你实际上做end--;,然后使用*end.很确定这0xFFFFFFFFFFFFFFFF几乎总是一个无效的地址......
如果你实际上正在测试if(*str!='\0')那么你应该仍然只是返回(一个空字符串是"不可逆转的" - 或者更确切地说,它不需要任何被认为是逆转的东西).
顺便说一句,我更喜欢使条件明确(就像我刚才那样); 它不仅更清楚地表明你的意图,而且如果你做了if(str!='\0')或者if(*str != NULL)因为你比较的类型是不兼容的,编译器可能会抱怨.这意味着您将拥有更强大,更易读,更有可能按照您的意图执行的代码.