【问题标题】:Pointers: Expression is not assignable指针:表达式不可赋值
【发布时间】:2015-04-29 19:28:48
【问题描述】:

我正在编写一个函数,其目的是更改结构变量的值。我收到错误消息,指出我的第一个函数末尾的表达式不可分配。那么,如何让函数更改 daate 结构的值?

这是我的代码:

#include <stdio.h>
#include <stdbool.h>

struct date
{
    int month;
    int day;
    int year;
};

struct date dateUpdate (struct date *dait) {
    struct date tomorrow;
    int numberOfDays (struct date d);

    if (dait->day != numberOfDays (*dait) ) {
        tomorrow.day = dait->day + 1;
        tomorrow.month = dait->month;
        tomorrow.year = dait->year;
    }
    else if ( dait->month == 12 ) { //end of year
        tomorrow.day = 1;
        tomorrow.month = 1;
        tomorrow.year = dait->year + 1;
    }
    else { //end of month
        tomorrow.day = 1;
        tomorrow.month = dait->month + 1;
        tomorrow.year = dait->year;
    }

    &dait->day = tomorrow.day;
    &dait->month = tomorrow.month;
    &dait->year = tomorrow.year;

    return *dait;
}

//Function to find the number of days in a month;

int numberOfDays (struct date d)
{
    int days;
    bool isLeapYear (struct date d);
    const int daysPerMonth[12] = 
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    if ( isLeapYear (d) && d.month == 2 )
        days = 29;
    else
        days = daysPerMonth[d.month - 1];

    return days;
}

}

int main (void) {
    struct date daate;
    daate.day = 21;
    daate.month = 6;
    daate.year = 2013;

    dateUpdate(&daate);
    printf("%d", daate.day);
}

【问题讨论】:

  • 当你通过引用传递时,为什么 dateUpdate() 返回一个值?

标签: c function pointers structure


【解决方案1】:

正确的语法(您已经在函数中使用)如下

dait->day = tomorrow.day;
dait->month = tomorrow.month;
dait->year = tomorrow.year;

考虑到这三个语句你可以简单地写

*dait = tomorrow;

【讨论】:

    【解决方案2】:

    dait 已经是一个指针,所以&amp;dait 是一个指向指针的指针,因此它没有要取消引用的字段。

    解决方案:在dait 之前丢失&amp;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2013-01-02
      相关资源
      最近更新 更多