c - Clarification about precedence of operators
问题描述
I got this snippet from some exercises and the question: which is the output of following code:
main()
{
char *p = "ayqm";
printf("%c", ++*(p++));
}
My expected answer was z
but the actual answer was in fact b
. How is that possible?
Later edit: the snippet is taken as it is from an exercise and did not focus on the string literal or syntax issues existent in other than the printf()
code zone.
解决方案
Your program is having undefined behavior because it is trying to modify the string literal "ayqm". As per the standard attempting to modify a string literal results in undefined behavior because it may be stored in read-only storage.
The pointer p
is pointing to string literal "ayqm". This expression
printf ("%c", ++*(p++));
end up attempting to modify the string literal that pointer p
is pointing to.
An undefined behavior in a program includes it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.
推荐阅读
- katalon-studio - Katalon Studio 中的报表修改
- javascript - 使用输入字段将表单转换为 PDF
- azure - 如何部署 Azure Logic App 和先决条件?
- android-ndk - 调用 env->SetStaticIntField(cls, jfid, 0) 方法时如何修复崩溃
- asp.net-core - 当期望修改的对象时,视图在提交时发布了一个空对象
- linux - 文件名操作
- android - 如何连接到设备 BLE?
- c# - 在我的串行通信程序中启用 dtr 时出现问题
- django - 在我的 Django 应用程序中运行 celery beat worker
- ios - 如何在 Xcode 中应用 Deeplab V3 进行实时分割?