如果静态声明的字符数组与指定的大小在C语言的文字进行初始化? [英] Should statically-declared character arrays with a specified size be initialized with a literal in C?

查看:143
本文介绍了如果静态声明的字符数组与指定的大小在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 字符一个数组,并填写与第3个元素A'b''C',并用其余元素'\\ 0'

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 '\0'".

在第二个,你不初始化数组什么。那么你想分配给数组,这是从来没有有效。像这样将工作:

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";

但意思会略有不同(取值现在是一个的指针的,不是的阵列的)。在大多数情况下,所不同的是最小的。但是,有几个重要的注意事项,比如你不能修改其内容。此外,的sizeof(S)将给予你一个指针的大小,而在原来的code,它会给你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

Recommended reading is this: http://c-faq.com/charstring/index.html.

这篇关于如果静态声明的字符数组与指定的大小在C语言的文字进行初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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