定义结构变量的字符串值

Nag*_*tri 2 c structure

我刚刚接受了某些面试问题.得到这个结构相关的问题,我不明白输出结果是什么,如果有人可以解释原因.

何时在结构中使用字符指针

#include <stdio.h>

struct name {
    char *array;
}variable;

int main( int argc, char * argv[] ){

    variable.array="hello";
    printf( "%s\n", variable.array );
}
Run Code Online (Sandbox Code Playgroud)

hello打印输出,但将结构变量更改为

struct name {
    char array[10];
}variable;
Run Code Online (Sandbox Code Playgroud)

编译器抛出错误"赋值中的不兼容类型"

variable.array="hello";
Run Code Online (Sandbox Code Playgroud)

我真的很困惑,我错过了这一点.为什么它会像分配问题一样显示错误?请指正,谢谢

Kum*_*lok 7

您只能在声明时初始化类似的数组,否则您需要使用

strcpy(variable.array,"hello");
Run Code Online (Sandbox Code Playgroud)

你甚至不能用简单的char数组做那样的事情

char a[10];

a="hello";
Run Code Online (Sandbox Code Playgroud)

编者会告诉:

incompatible types when assigning to type ‘char[10]’ from type ‘char *’
Run Code Online (Sandbox Code Playgroud)

因为"hello"是一个字符串文字,由指针保存,不能像这样分配给数组.