是否应该用 C 中的文字初始化具有指定大小的静态声明的字符数组? [英] Should statically-declared character arrays with a specified size be initialized with a literal in C?

查看:35
本文介绍了是否应该用 C 中的文字初始化具有指定大小的静态声明的字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,

gcc 编译这个没问题...

gcc compiles this ok...

char s[7] = "abc";

但它给出了错误分配中不兼容的类型"...

But it gives the error "incompatible types in assignment" with...

char s[7];
s = "abc";

有什么区别?

推荐答案

第一个是初始化;它的意思是在堆栈上声明一个由 7 个 char 组成的数组,并用 'a''b''c',其余元素用 ''".

The first one is an initialization; it means "declare an array of 7 char on the stack, and fill the first 3 elements with 'a', 'b', 'c', and the remaining elements with ''".

在第二个中,您没有将数组初始化为任何内容.然后,您尝试分配给该数组,该数组永远无效.像这样的东西会起作用":

In the second one, you're not initializing the array to anything. You're then trying to assign to the array, which is never valid. Something like this would "work":

const char *s;
s = "abc";

但含义会略有不同(s 现在是指针,而不是数组).在大多数情况下,差异很小.但是有几个重要的警告,例如您不能修改内容.此外,sizeof(s) 会给你一个指针的大小,而在你的原始代码中,它会给你 7(数组的大小).

But the meaning would be slightly different (s is now a pointer, not an array). In most situations, the difference is minimal. But there are several important caveats, for instance you cannot modify the contents. Also, sizeof(s) would given you the size of a pointer, whereas in your original code, it would have given you 7 (the size of the array).

推荐阅读是这样的:http://c-faq.com/charstring/index.html.

这篇关于是否应该用 C 中的文字初始化具有指定大小的静态声明的字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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