用char初始化结构体的函数-解释我的警告



有人知道为什么下面的代码不能与char s一起工作吗?它与int s一起工作,但当我想使用char来初始化结构时,它会失败并给出警告,如:

warning: assignment makes integer from pointer without a cast

我不知道这个警告是什么意思

#include <stdio.h>
#include <stdlib.h>
struct complex {
int re;
int im;
char name;
};
struct complex initialize (int k, int l, char nazwa)
{
    struct complex x;
    x.re = k;
    x.im = l;
    x.name= nazwa;
    return x;
}

int main ()
{
    struct complex e;
    struct complex f;
    int a;
    int b;
    char o;
    int c;
    int d;
    char p;
    a=5;
    b=6;
    o="t";
    e = initialize (a, b, o);
    c=8;
    d=3;
    p="u";
    f=initialize (c, d, p);
    printf("c1 = (%d,%d)nc2 = (%d,%d)n name 1=%s name 2=%sn", e.re , e.im, f.re, f.im, e.name, f.name);
    return 0;
}

"u"不是字符。它是一个字符串。一个字符数组。你需要的是'u'。但是,这样您将只有一个字符的名称,并且您需要将printf中的%s替换为%c

除非你真的想要一个字符串,如果是这样的话,把struct中的char改成const char*。函数形参也是如此:

struct complex {
    int re;
    int im;
    const char* name;
};
struct complex initialize (int k, int l, const char* nazwa) {
...
}
const char* o;
const char* p;

注意,你可以初始化变量和结构体。你的代码可以像这样:

void print_complex(int n, struct complex c) {
    printf("c %d = (%d,%d)n", n, c.re , c.im);
    printf("name=%sn", c.name);
}
int main () {
    struct complex e = { 5, 6, "t" };
    struct complex f = { 8, 3, "u" };
    print_complex(1, e);
    print_complex(2, f);
    return 0;
}

相关内容

最新更新