英文:
C pointer mistakes in my understanding of the problem
问题
执行后的输出结果为:
#include<stdio.h>
int main()
{ char str[]="xyz",*ps=str;
while(*ps)
ps++;
for(ps--;ps-str>=0;ps--)
puts(ps);
return 0;
}
正确答案是:
z
yz
xyz
我的逻辑是:
在while(*ps) ps++;
之后,*ps
表示数组的最后一个元素,即" "
当执行代码for(ps--;ps-str>=0;ps--)puts(ps);
时,*ps
每次向前移动两个位置。
所以我认为答案应该是
z
xyz
英文:
The output result after execution is______<br/>
#include<stdio.h>
int main()
{ char str[]="xyz",*ps=str;
while(*ps)
ps++;
for(ps--;ps-str>=0;ps--)
puts(ps);
return 0;
}
The right answer is <br/>
z
<br/>
yz
<br/>
xyz
<br/>
My logic is<br/>
After while(*ps) ps++;
*ps
represents " "
the last element of the array<br/>
When execute codefor(ps--;ps-str>=0;ps--)puts(ps);
,*ps
go back two positions everytime.
So I think t should be <br/>
z
<br/>
xyz
<br/>
答案1
得分: 2
可能更接近你想要的:
int main()
{
char str[]="xyz";
size_t length = sizeof(str)-1;
// size_t length = strlen(str); // 更安全的版本。
for (size_t i = 0; i < length; i++)
{
char* ps = str+length-i-1;
puts(ps);
}
}
英文:
Probably closer to what you want:
int main()
{
char str[]="xyz";
size_t length = sizeof(str)-1;
// size_t length = strlen(str); // safer version of above.
for (size_t i = 0; i < length; i++)
{
char* ps = str+length-i-1;
puts(ps);
}
}
答案2
得分: 1
No, *ps
is then '\0'
.
No, it does not. It starts by going back one step, then in each iteration it only goes back one step. It's the same as doing this:
{
ps--; // for(ps--; ...; ...)
while(ps-str >= 0) { // for(...; ps-str >= 0; ...)
puts(ps);
ps--; // for(...; ...; ps--)
}
}
ps-str>=0
is not a good test though. If you step ps
"behind" the start of str
the comparison is invalid.
A safe version could simply be:
#include <stdio.h>
int main() {
char str[] = "xyz", *ps = str;
while (*ps) ps++;
while (ps != str) {
--ps;
puts(ps);
}
}
英文:
> "After while(*ps) ps++;
*ps
represents " "
"
No, *ps
is then '\0'
.
> When execute code for(ps--;ps-str>=0;ps--)puts(ps);
, *ps
go back two positions everytime
No, it does not. It starts by going back one step, then in each iteration it only goes back one step. It's the same as doing this:
{
ps--; // for(ps--; ...; ...)
while(ps-str >= 0) { // for(...; ps-str >= 0; ...)
puts(ps);
ps--; // for(...; ...; ps--)
}
}
ps-str>=0
is not a good test though. If you step ps
"behind" the start of str
the comparison is invalid.
A safe version could simply be:
#include <stdio.h>
int main() {
char str[] = "xyz", *ps = str;
while (*ps) ps++;
while (ps != str) {
--ps;
puts(ps);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论