首页 > 解决方案 > 无法输出 C struct char 数组成员

问题描述

我正在学习如何在 C 中使用结构。但在下面的代码中,我无法打印 myArray "HELLO!" 声明为 char 数组:

#include <stdio.h>

struct myStruct
{
    int myInt;    
    float myFloat;
    char myArray[40];
};

int main()
{
    struct myStruct p1;
    
    p1.myInt = 80;
    p1.myFloat = 3.14;
    printf("Integer: %d\n", p1.myInt);
    printf("Float: %f\n", p1.myFloat);
    
    p1.myArray = "HELLO!";
    printf("Array: %s\n", p1.myArray);

    return 0;
}

上面的语法有什么问题,我没有得到“HELLO!” 作为输出?这里有问题:

p1.myArray = "HELLO!";
printf("Array: %s\n", p1.myArray);

标签: cstructvariable-assignmentc-stringschararray

解决方案


数组是不可修改的左值。因此,尝试将指针(字符串文字隐式转换为指向其第一个元素的指针)分配给数组指示符

p1.myArray = "HELLO!";

不会编译。

strcpy例如使用标准字符串函数

#include <string.h>

//...

strcpy( p1.myArray, "HELLO!" ); 

或者您可以在定义结构类型的对象时初始化数据成员,例如

struct myStruct p1 = { .myInt = 80, .myFloat = 3.14, .myArray = "HELLO!" };

或者

struct myStruct p1 = { .myInt = 80, .myFloat = 3.14, .myArray = { "HELLO!" } };

或者

struct myStruct p1 = { 80, 3.14, "HELLO!" };

或者

struct myStruct p1 = { 80, 3.14, { "HELLO!" } };

这是一个演示程序。

#include <stdio.h>
#include <string.h>

struct myStruct
{
    int myInt;    
    float myFloat;
    char myArray[40];
};

int main( void )
{
    struct myStruct p1 = { .myInt = 80, .myFloat = 3.14, .myArray = { "HELLO!" } };

    printf("Integer: %d\n", p1.myInt);
    printf("Float: %f\n", p1.myFloat);
    printf("Array: %s\n", p1.myArray);

    strcpy( p1.myArray, "BYE!" );
    
    printf("\nArray: %s\n", p1.myArray);

    return 0;
}

程序输出为

Integer: 80
Float: 3.140000
Array: HELLO!

Array: BYE!

推荐阅读