简体   繁体   English

将字符串分配给 C 中的 int

[英]Assign string to int in C

I have this code below:我在下面有这段代码:

#include <stdio.h>

int main(void) {
    int i = "hello world";

    printf("%d", i);

    return 0;
}

why assigning a string to int variable not giving me a compilation error, but prints a garbage value.为什么将string分配给int变量不会给我一个编译错误,而是打印一个垃圾值。

Edit 1:编辑1:

A lot of answers suggested to not ignore the warning.很多答案建议不要忽略警告。 I wrote this code on ideone, which unfortunately, did not give me any warning.我在ideone上写了这段代码,不幸的是,它没有给我任何警告。

I believe it would perform a pointer to int conversion.我相信它会执行一个指向 int 转换的指针。 It should be a warning indicating the conversion without cast.它应该是一个警告,表明没有强制转换。

int i = "hello world";

With that you assigning the address of the string literal "hello world" in memory to the int object i , which is in most cases undefined behavior because the value of a memory location is in many cases beyond the area an object of type int can hold. With that you assigning the address of the string literal "hello world" in memory to the int object i , which is in most cases undefined behavior because the value of a memory location is in many cases beyond the area an object of type int can hold .

This undefined value is then printed by:然后通过以下方式打印此未定义值:

 printf("%d", i);

Nonetheless the compiler should give you a warning when doing that without an explicit cast, fe as I compiled your code by gcc it gave:尽管如此,编译器应该在没有显式转换的情况下给你一个警告,因为我通过 gcc 编译了你的代码,它给出了:

warning: initialization of 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]警告:从 'char *' 初始化 'int' 使得 integer 从没有强制转换的指针 [-Wint-conversion]

Do never ignore compiler warnings.永远不要忽略编译器警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM