字符数组声明和初始化用C [英] Char array declaration and initialization in C

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

问题描述

我很好奇,为什么这不是在C允许的:

I was curious about why this is not allowed in C:

char myarray[4];

myarray = "abc";

这是允许的:

char myarray[4] = "abc";

我知道,在第一种情况下,我应该使用的strcpy

char myarray[4];

strcpy(myarray, "abc");

但为什么声明,后来初始化是不允许的,申报和同时初始化被允许?它与C程序的内存映射?

But why declaration and later initialization is not allowed and declaration and simultaneous initialization is allowed? Does it relate to memory mapping of C programs?

谢谢!

推荐答案

这是因为你的第一个code段未执行的初始化的,但是的分配的:

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

和数组是不是在C直接分配。

And arrays are not directly assignable in C.

名称 myarray中其实解析为它的第一个元素的地址(&放大器; myArray的[0] ),这是不是一个左值,因此不能作为赋值的目标。

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

这篇关于字符数组声明和初始化用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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