Ram*_*ami 1 c string printf pointers
我接受了一次采访,我得到了这段代码,并询问每个printf语句的输出是什么.
我的答案是评论,但我不确定其余的.
任何人都可以解释陈述1,3和7的不同输出以及为什么?
谢谢!
#include <stdio.h>
int main(int argc, const char * argv[]) {
char *s = "12345";
printf("%d\n", s); // 1.Outputs "3999" is this the address of the first pointer?
printf("%d\n", *s); // 2.The decimal value of the first character
printf("%c\n", s); // 3.Outputs "\237" What is this value?
printf("%c\n", *s); // 4.Outputs "1"
printf("%c\n", *(s+1)); // 5.Outputs "2"
printf("%s\n", s); // 6.Outputs "12345"
printf("%s\n", *s); // 7.I get an error, why?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个电话
printf("%d\n", s);
Run Code Online (Sandbox Code Playgroud)
具有未定义的行为,因为无效的格式说明符与指针一起使用.
这个电话
printf("%d\n", *s);
Run Code Online (Sandbox Code Playgroud)
输出字符的内部代码(例如ASCII代码)'1'.
这个电话
printf("%c\n", s);
Run Code Online (Sandbox Code Playgroud)
由于使用带指针的无效格式说明符,因此具有未定义的行为.
这些电话
printf("%c\n", *s);
printf("%c\n", *(s+1));
Run Code Online (Sandbox Code Playgroud)
是有效的.第一个输出字符'1',第二个输出字符'2'.
这个电话
printf("%s\n", s);
Run Code Online (Sandbox Code Playgroud)
是正确的并输出字符串"12345".
这个电话
printf("%s\n", *s);
Run Code Online (Sandbox Code Playgroud)
无效,因为无效的格式说明符与该类型的对象一起使用char.