为什么我不能在代码中的 %s 之后打印 %c?



我是C编程的新手,正在学习获取字符串输入。我尝试使用malloc:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^n]", s);
s = realloc(s, strlen(s) + 1);    

printf("%s ",s[2]);
printf("%c",s[2]);
return 0;
}

运行此操作时,不会打印任何内容。但是当我把%c printf放在%s printf:之前时

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^n]", s);
s = realloc(s, strlen(s) + 1);    
printf("%c",s[2]);
printf("%s ",s[2]);

return 0;
}

它运行并显示printf("%c",s[2]);的结果。为什么会发生这种情况?printf是否清除char s中的内存?

在C中,字符串只是char的数组,我们将其保存为char *:计算机内存中存储char数组的位置(内存地址指针(。

%c标志告诉printf处理单个字符(即s[2](。

然而,%s标志告诉printf处理存储在s[2]存储器地址处的整个字符串。例如,如果s[2] = 'A',则printf将尝试访问存储在存储器位置'A'处的字符串。在ASCII中,字母'A'只是整数65,这不是有效的内存位置,因此程序将出错。

在第一种情况下,程序可能在使用%cprintf输出之前退出(由于使用%s时的错误(,而在第二种情况中,使用%cprintf在错误发生之前输出。

最新更新