我是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
,这不是有效的内存位置,因此程序将出错。
在第一种情况下,程序可能在使用%c
的printf
输出之前退出(由于使用%s
时的错误(,而在第二种情况中,使用%c
的printf
在错误发生之前输出。