C:不兼容的类型? [英] C: Incompatible types?

查看:187
本文介绍了C:不兼容的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdlib.h>
#include <stdio.h>

struct foo{
    int id;
    char *bar;
    char *baz[6];
};

int main(int argc, char **argv){
    struct foo f;   
    f.id=1;

    char *qux[6];

    f.bar=argv[0];
    f.baz=qux;  // Marked line

    return 1;
}

这只是一些测试code所以忽略qux实际上不会有任何在它有用。

This is just some test code so ignore that qux doesn't actually have anything useful in it.

我在标记线分配到类型的char * [6]从类型时,得到一个错误,不兼容的类型'字符** ,但两者的变量定义为的char * [6] 在code。任何见解?

I'm getting an error on the marked line, incompatible types when assigning to type ‘char *[6]’ from type ‘char **’ but both of the variables are defined as char *[6] in the code. Any insight?

推荐答案

本code的问题是该行

The problem with this code is that the line

f.baz=qux;

试图数组 qux 分配给数组巴兹。在C中,阵列是不变量,不能分配新值。要看到一个简单的例子,这个code:

Tries to assign the array qux to the array baz. In C, arrays are not variables and cannot be assigned new values. To see a simpler example, this code:

int arr1[10], arr2[10];
arr1 = arr2; // Error!

时非法的,因为在第二行试图第二阵列分配第一值,这是不是在C不允许

Is illegal because the second line tries to assign the second array the value of the first, which is not allowed in C.

要解决这个问题,你可能会想要写一个显式循环的元素拷贝过来,因为在这里看到:

To fix this, you'll probably want to write an explicit loop to copy the elements over, as seen here:

int i;
for (i = 0; i < 6; ++i)
    f.baz[i] = qux[i];

这是合法的,因为数组中的每个元素是一个的char * ,它可以分配。

This is legal because each individual element of the array is a char *, which can be assigned.

您有时还可看到的memcpy 用于指定数组:

You sometimes also see memcpy used to assign arrays:

memcpy(f.baz, qux, sizeof f.baz);

这比复制阵列中的所有字段的原始字节。

This copies over the raw bytes of all the fields in the arrays.

这篇关于C:不兼容的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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