你好,我有这段代码用指针填充数组并用指针打印它。结果是假的。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int main(){
int p;
char po[8];
char *i;
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
}
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
return 0;
}
我错在哪里?
最佳答案
增加指针可能有充分的理由。只是不要忘记在重新使用它们之前将它们重置为初始值!
您的代码应该是:
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
} /* i is now po + 8 ... */
i = po;
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
现在你应该学会不写这样的代码:
- block 没有缩进 => 更难阅读
- 从未测试过 scanf 的值:文件末尾会发生什么(类 Unix 上的 Ctrl-D,Windows 上的 Ctrl-Z)?
- 连一条评论都没有...
关于c - 带有指向数组指针的 printf scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33971966/