我正在玩弄我的一张演讲幻灯片中的这段代码,我的一个问题是打印数组时为什么我们不能使用指针而不是只打印“a”,在打印的最后一行声明
printf("\n message after decryption: %s\n", a);
我不明白为什么我们不能使用指针来打印数组。有人可以向我解释为什么不能这样做吗?
printf("\n message after decryption: %s\n", *q);
#include <stdio.h>
#define NUM 78
int main()
{
int i = 0;
char a[] = "Hello CSE 240";
printf("\n message: %s\n ", a);
while(a[i] != '\0'){a[i] = *(a+i)+1;i++;}
printf("\n message after encryption: %s\n ", a);
char *q = a;
while(*q != '\0'){*q = *q-1;q++;}
printf("\n message after decryption: %s\n", a);
}
最佳答案
您想在 q
修改循环之后打印出数组的内容,但在所有增量之后它指向空终止字符,即 '\0'
- 因此在 printf
中使用 q
将仅打印此信息 - 解密后的消息:
- 修改后的数组/字符串将不会打印。
要使用 q
来完成,您需要在 while 循环结束后将 q
重新分配给数组的第一个元素:q=a
.
然后这条语句将如你所愿地工作:
printf("\n message after decryption: %s\n", q);
很高兴您使用合适的格式说明符更改了打印语句。
关于你能在指向数组的指针中打印内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867883/