gpt4 book ai didi

c - 将字符串存储在C中的整数变量中

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:07 25 4
gpt4 key购买 nike

#include <stdio.h>
int main()
{
int a = "Hi";
char b = 'F';

int c = a + b;

printf("%d",a); /* (1) */
printf("%d",c); /* (2) */
}

为什么指令(1)的输出是18537?它如何按照 ANSI 标准存储值

说明 (2) 很清楚,因为我们基本上是将 70 加到 18537,得到 18607

有人可以详细说明如何根据字符串将值存储在整数变量中吗?

最佳答案

胜利的编译器警告!

$ cc -Wall -Wextra e.c 
e.c: In function ‘main’:
e.c:4:13: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
int a = "Hi";
^~~~

您将字符串文字的内存地址分配给变量a。好吧,在很多情况下你会这样做。然而,这并不能保证,并且存在与此相关的潜在问题。例如,int 可能不足以保存整个地址。

可能值得指出的是,这不是有效的 C 代码,所以不要这样做。根据https://port70.net/~nsz/c/c11/n1570.html#6.5.16.1p1 (感谢@Lundin 提供链接):

One of the following shall hold:112)

  • the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type;
  • the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand is an atomic, qualified, or unqualified pointer, and the right is a null pointer constant; or
  • the left operand has type atomic, qualified, or unqualified _Bool, and the right is a pointer.

参见 Lundin's answer了解如何强制编译器不接受无效代码。

关于c - 将字符串存储在C中的整数变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com