C 数组声明和赋值? [英] C array declaration and assignment?

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

问题描述

我在这里问了一个关于结构的类似问题,但我正在尝试弄清楚 C 如何处理诸如分配变量之类的事情,以及为什么在功能相同的情况下不允许将它们分配给彼此.

I've asked a similar question on structs here but I'm trying to figure out how C handles things like assigning variables and why it isn't allowed to assign them to eachother if they are functionally the same.

假设我有两个数组:

int x[10];  
int y[10];  

为什么 x = y 不能编译?如果他们都是这样的签名",那么你不应该来回分配他们吗?

Why won't x = y compile? If they are both the same "signature" like that, then shouldn't you be able to assign them back and forth?

我能否以一种允许我在 C 中执行此操作的方式声明这些内容?对我来说你可以这样做是有道理的,但也许有办法做到这一点?结构体的类型定义似乎是解决方案,数组声明和赋值是否相同?

Can I declare these in a way that would allow me to do that in C? It makes sense to me that you would be able to, but maybe there is a way that this can be done? Typedefs for structs seemed to be the solution, would it be the same for array declaration and assignment?

感谢你们的帮助,我是 Stackoverflow 的新手,但到目前为止它对我来说是一个非常好的资源!

I appreciate your guys help, I'm new to Stackoverflow but it has been a really good resource for me so far!

推荐答案

简单地说,数组是不可赋值的.它们是不可修改的左值".这当然引出了一个问题:为什么?请参阅此问题以获取更多信息:

Simply put, arrays are not assignable. They are a "non-modifiable lvalue". This of course begs the question: why? Please refer to this question for more information:

为什么 C++支持结构内数组的成员分配,但一般不支持?

数组不是指针. x 这里确实指的是一个数组,尽管在许多情况下它衰减"(隐式转换)指向其第一个元素的指针.同样,y 也是数组的名称,而不是指针.

Arrays are not pointers. x here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y too is the name of an array, not a pointer.

您可以在结构中进行数组赋值:

You can do array assignment within structs:

struct data {
    int arr[10];
};

struct data x = {/* blah */};
struct data y;
y = x;

但是你不能直接用数组来做.使用 memcpy.

But you can't do it directly with arrays. Use memcpy.

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

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