将值分配给char数组 [英] Assigning value to char array

查看:131
本文介绍了将值分配给char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入时没有错误

char a[10] = "Hi";

但是当我把它改成下面的时候,我得到一个错误: Array type char不可分配。

But when I change it to the following, I get an error: Array type char is not assignable.

char a[10];
a = "Hi";

为什么数组类型char不能赋值?是因为语言是有意义地写的,还是我缺少一个点?

Why is array type char not assignable? Is it because the language is written that way on purpose or am I missing a point?

推荐答案

正如我上面所说的,将使用 std :: string 而不是 char []

The C++ way of doing this, as I commented above, would be to use std::string instead of char[]. That will give you the assignment behavior you're expecting.

也就是说,第二种情况只会得到一个错误的原因是 = 表示不同的东西:

That said, the reason you're only getting an error for the second case is that the = in these two lines mean different things:

char a[10] = "Hi";
a = "Hi";

第一个是初始化,第二个是赋值。

The first is an initialization, the second is an assignment.

第一行在堆栈上分配足够的空间来保存10个字符,并将前三个字符初始化为H,i和\0。从这一点开始,所有 a 都是指数组在堆栈上的位置。因为数组只是堆栈上的一个位置,所以不允许改变 a 。如果你想在堆栈上的不同位置保存一个不同的值,你需要一个不同的变量。

The first line allocates enough space on the stack to hold 10 characters, and initializes the first three of those characters to be 'H', 'i', and '\0'. From this point on, all a does is refer to the position of the the array on the stack. Because the array is just a place on the stack, a is never allowed to change. If you want a different location on the stack to hold a different value, you need a different variable.

另一方面,第二个(无效)改变 a 以指代Hi的(技术上不同的)咒语。这是不允许的上述原因。一旦你有一个初始化的数组,你可以做的唯一的事情是从它读取值和写入值。您不能更改其位置或大小。这是作业在这种情况下会尝试做的。

The second (invalid) line, on the other hand, tries to change a to refer to a (technically different) incantation of "Hi". That's not allowed for the reasons stated above. Once you have an initialized array, the only thing you can do with it is read values from it and write values to it. You can't change its location or size. That's what an assignment would try to do in this case.

这篇关于将值分配给char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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