C语言复活节计算程序报assignment to expression with array type错误如何解决
报错原因
你遇到的assignment to expression with array type错误由代码中month = "March"、month = "April"两行赋值语句触发:
C语言中char month[50]定义的是字符数组,数组名是不可修改的左值,本质是固定的内存地址常量,不支持直接用等号给整个数组赋值字符串字面量。
修复方案
有两种常用修复方式:
方案1:使用strcpy函数拷贝字符串
需要先引入<string.h>头文件,将字符串字面量拷贝到month数组的内存空间中,修改后完整代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char month[50]; int year, day; printf("Please enter a year between 1990 and 2099: "); scanf("%d", &year); int a = year-1900; int b = a%19; int c = (7*b+1)/19; int d = (11*b+4-c)%29; int e = a/4; int f = (a+e+31-d)%7; int g = 25 - (d + f); if (g <= 0 ) { strcpy(month, "March"); day = 31 + g; } else { strcpy(month, "April"); day = g; } printf("The date is %s %d", month, day); return 0; }
方案2:将month改为字符指针类型
字符指针可以直接指向字符串字面量的首地址,不需要额外数组内存空间,仅需修改month的定义即可兼容原有赋值逻辑:
// 把原来的char month[50];替换为下面这行 char *month;
补充说明:如果你需要严格校验用户输入为1991-2099区间的年份,可以在
scanf读取年份后增加合法性判断逻辑,拦截不符合要求的输入。
内容的提问来源于stack exchange,提问作者Michael Angelo Magante
相关产品推荐
相关产品推荐

