c - 无法输出 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);
解决方案
数组是不可修改的左值。因此,尝试将指针(字符串文字隐式转换为指向其第一个元素的指针)分配给数组指示符
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!
推荐阅读
- php - CodeIgniter - 找不到类“CI_Loader”
- r - 使用 cowplot 和 ggplot2 在某些行周围绘制边框
- java - Java/AEM:com.day.cq.commons.Externalizer absolutelink 函数返回错误的主机名
- reactjs - Styled-Components 重新加载后丢失样式
- r - 按一列中的值组织数据
- c++ - QTreeWidgetItem 设置不可选择清除选择
- javascript - 如何在 JavaScript 中执行不区分大小写的替换?
- flutter - 颤振:flutter_markdown 字体大小
- javascript - 一旦鼠标不再存在,隐藏按钮内容 JS
- delay - robots.txt 中 crawl-delay 的最大值是多少?