从嵌套函数调用结构的指针

时间:2011-11-27 19:47:36

标签: c pointers struct

我有一个调用结构的问题,将它们作为参数放在void函数中,然后调用另一个void函数,参数采用相同的结构,所以我把它们都指向并且结果没有显示出来。如果我单独调用它们,它可以工作,但是使用嵌套函数,它不起作用。

#include <stdio.h>
#include <stdlib.h>

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

void next_day(date *d,int days)
{
        if(d->day < days) {
                int m = d->day + 1;
                d->day = m;
        }
        else
        {
                int m = d->year + 1;
                d->year = m;
                d->month = 1;
        }
}

void tom(date *d)
{
        switch(d->month)
        {
                case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                        next_day(&d,31);
                        break;
                case 4: case 6: case 9: case 11:
                        next_day(&d,30);
                        break;
                case 2:
                        if(d->year % 4 == 0)
                                next_day(&d,29);
                        else
                                next_day(&d,28);
                        break;
        }
}

int main(void)
{
        //date d = malloc(sizeof(date));
        date d;
        printf("Enter day, month, year: ");
        scanf("%d %d %d",&(d.day),&(d.month),&(d.year));
        tom(&d);
        printf("The next day is: %d %d %d",d.day,d.month,d.year);
        return 0;
}

提前感谢任何想要查看代码的人。

2 个答案:

答案 0 :(得分:1)

我很确定您的问题出在next_day(&d,31);您已经拥有了结构的地址,您不需要再次使用&运算符。尝试使用next_day(d,31);调用它。

这应该出现在编译器警告中;总是注意阅读那些警告。

答案 1 :(得分:1)

next_day(&d,31);   // At this point `d` is a pointer to a struct type. 

您正在发送指针的地址,这意味着在接收端,函数参数需要是指向指针的指针(即date **)。但在你的情况下,它不是。

void next_day(date *d,int days)

所以,只做 -

next_day(d,31);  // Notice the removal of & 

现在d的类型为date *,接收端的参数类型为date *

相关问题