为什么char初始化有区别? C [英] Why char initialization difference? C

查看:113
本文介绍了为什么char初始化有区别? C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这两种初始化数组的方式互不相同?

Why are those two ways of initializing an array different from each other?

第一次初始化给我一个编译器警告:

The first initialization gives me a compiler warning:

第二个就可以了.

char *c_array_1[] = { {'a','b','c','d','e'}, {'f','g','h','i','j'} };

char *c_array_2[] = {"abcde","fghij"};

推荐答案

因此,在C语言中,字符串文字(例如:"abcde")自动在编译器的后台获取为其分配的存储空间.

So, in the C language, string literals (like: "abcde") automatically get storage allocated for them in the background of the compiler.

所以,当您这样做

char *c_array_2[] = {"abcde","fghij"};

在某种程度上,编译器可以将其更改为:

The compiler can, to some degree, change that to:

char *c_array_2[] = {Some_Pointer, Some_Other_Pointer};

但是,对于另一个示例:

However, for the other example:

char *c_array_1[] = { {'a','b','c','d','e'}, {'f','g','h','i','j'} };

编译器将尝试初始化.这将导致此行代码转换为以下代码(可能会发出一些警告):

The compiler will attempt to initialize. This will cause this line of code to be converted to the following (And probably push out a few warnings):

char *c_array_1[] = {'a', 'f'};

然后这肯定不是您想要的('a'很可能不是有效的指针.您可以从此问题中看到有关初始化发生原因的更多信息:

And then this is certainly not what you want ('a' is very likely not a valid pointer. You can see some more information on why the initialization happens like that from this question: Why is this valid C

这篇关于为什么char初始化有区别? C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆