分配给相同类型的变量时出现 C 不兼容类型错误

发布于 2024-11-28 19:20:50 字数 410 浏览 0 评论 0原文

我有以下代码:

typedef unsigned char some_type[6];

int main() {
        some_type some_var1;
        some_type some_var2;
        some_var1 = some_var2;
        return 0;
}

当我尝试编译它时,我收到以下错误消息:

incompatible types when assigning to type 'some_type' from type 'unsigned char *'

这是为什么?两个变量的类型完全相同?我该怎么做才能让它发挥作用?我无法更改 typedef,因为它是我正在使用的 API 的一部分。

I have the following code:

typedef unsigned char some_type[6];

int main() {
        some_type some_var1;
        some_type some_var2;
        some_var1 = some_var2;
        return 0;
}

And when i try to compile it, I get the following error message:

incompatible types when assigning to type 'some_type' from type 'unsigned char *'

Why is this? Both variables are exactly the same type? What can I do to make it work? I can't change the typedef, as it is part of an API I am using.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小红帽 2024-12-05 19:20:50

你不能像这样互相分配数组。如果这些是字符串,请使用 strcpy:

strcpy(some_var1, some_var2);

如果不是,请使用 memcpy:

memcpy(&some_var1, &some_var2, sizeof (some_type));

You can't assign arrays to each other like that. If these are strings, use strcpy:

strcpy(some_var1, some_var2);

If not, use memcpy:

memcpy(&some_var1, &some_var2, sizeof (some_type));
如果没有 2024-12-05 19:20:50

数组不能以这种方式复制。复制数组的常用方法是使用memcpy。

Arrays can't be copied in that way. The usual way to copy arrays is by using memcpy.

空城旧梦 2024-12-05 19:20:50

您不能将一个数组分配给另一个数组,因为数组会衰减为常量指针。此外,您可能不想只将一个数组的地址复制到另一个变量中。您需要使用诸如 memcpy 之类的东西。

You can't assign one array to the other because arrays decay to constant pointers. Besides, you probably wouldn't want to just copy the address of one array into the other variable. You'll need to use something like memcpy.

孤星 2024-12-05 19:20:50

您应该为此使用 memcpy,因为 C 并不真正支持以这种方式复制结构。

memcpy(&some_var1, &some_var2, sizeof(some_var));

You should use memcpy for this as C doesn't really support copying of structures this way.

memcpy(&some_var1, &some_var2, sizeof(some_var));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文