【问题标题】:compile error of "incompatible types when assigning to type char[2] from type int从 int 类型分配给类型 char[2] 时出现“不兼容类型”的编译错误
【发布时间】:2012-04-30 03:29:26
【问题描述】:

我遇到了上述编译错误。这行代码是这样的:

if ((strcmp(tempDept, data[1].Dept)==0) && tempCourse == data[i].course){
            if (tempDay = data[i].meet_days &&
                tempTime == data[i].start.hour){  //<---This line
                    printf("this worked");
            }
        }

这是我的结构声明:

typedef enum {MW, TR} days;

typedef struct {
  int hour, min;
} Time;

typedef struct {
  char Dept[5];
  int course, sect;
  days meet_days;
  Time start, end;
  char instr[20];
} sched_record;

这是我的变量列表:

int switchInput;
int i = 0;
int tempCourse = 0;
char tempDept[5];
char tempDay[2];
int tempTime;
//char tempTime[1];
FILE *filePointer;
sched_record data[MAX_RECORD];

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: c sockets


    【解决方案1】:
    tempDay = data[i].meet_days
    

    这会引起问题,因为tempDay 是长度为 2 的字符数组,而 meet_days 是枚举 days。在 C 中,枚举中的常量只是 int 类型。另一个不能将int 分配给char array 本身的问题。也许您想要一个等号 == ? 现在您必须考虑如何将int 枚举值转换为char[2]。一种方法是使用sprintf() 来实现这一点。但具体实现取决于您对枚举常量的解释。

    【讨论】:

      【解决方案2】:
      if (tempDay = data[i].meet_days
      

      您缺少双等号 ==

      【讨论】:

      • 很好,解决了错误,但现在我在添加双等号的行上收到comparison between pointer and integer 的警告:if (tempDay == data[i].meet_days &amp;&amp;
      • @user1318371 您正在尝试将字符串与无效的整数进行比较。您需要将一个转换为另一个。
      • @SethCarnegie 所以我假设我上面声明的枚举是一个字符串?我确实尝试过:if ((strcmp(tempDay,data[i].meet_days)==0) 并得到了incompatible type for argument 2 of strcmp
      • @user1318371 不,tempDay 是一个由两个 chars 组成的数组。
      • @user1318371 枚举不是字符串而是int 所以在这种情况下MW 等价于0
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多