【问题标题】:Error in assignment to expression with array type赋值给数组类型的表达式时出错
【发布时间】:2021-12-11 04:38:51
【问题描述】:

我正在尝试编写一个程序,当用户输入 1991 年到 2099 年之间的年份时显示复活节。一切都很好,但是当我尝试运行该程序时,它说有一个错误:赋值给表达式数组类型。我怎样才能解决这个问题?我的代码有什么问题?

#include <stdio.h>
#include <stdlib.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 )
{
    month = "March";
    day = 31 + g;
}
else
{
    month = "April";
    day = g;
}
    printf("The date is %s %d", month, day);

}

【问题讨论】:

  • 你不用=分配给字符串,你使用strcpy()
  • 您也可以将其更改为指针变量:char *month
  • 谢谢,它现在可以运行了
  • 最好避免滚动自己的日历功能。日历很奇怪。不过,在这种情况下,它可能勉强够用。
  • 始终检查scanf等的返回值,失败则中止(例如abort();)。

标签: arrays c variable-assignment c-strings string-literals


【解决方案1】:

数组没有赋值运算符。数组是不可修改的左值。

要更改数组的内容,例如使用标准字符串函数strcpy

#include <string.h >

//...

strcpy( month, "March" );

另一种方法是将变量月声明为指针。例如

char *month;

或者(这样更好)

const char *month;

在这种情况下你可以写

month = "March";

【讨论】:

  • "lvalue" 的字面意思是“可以在赋值的 LHS 上使用”。您的意思是“右值”吗?
  • @ikegami 否根据 C 标准数组是不可修改的左值。
  • 好的,但是很奇怪
  • @ikegami 术语的起源是指它们出现在作业中的位置,语言细节有时会使这些含义不适用。左值是表示内存位置的表达式,而右值是没有关联位置的值(它可以是表达式中的临时值)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
  • 2017-06-12
  • 1970-01-01
相关资源
最近更新 更多