为什么我会得到这些随机值?

时间:2014-10-14 01:29:22

标签: c function pointers

好的,所以我必须编写一个使用指针将日期转换为年,周和日的函数。这是功能。

int convertTime(int days, int *y, int *w, int *d){
  if (days < 0 || y == NULL || w == NULL || d == NULL){
    printf("An error has occured\n");
    return 1;
  }else{
    *y = days / 365;
    *w = (days % 365) / 7;
    *d = ((days % 365) / 7) % 7)
    return 0;
  }
}

以下是我在调用它的主函数中的部分。

// Tests convertTime
  int days = 1000;
  int y2 = 0, w2 = 0, d2 = 0;
  int *y = NULL, *w = NULL, *d = NULL;
  y = &y2, w = &w2, d = &d2;
  convertTime(days, y, w, d);
  printf("Expected output: 2 years, 38 weeks, 4 days\n");
  printf("Actual output: %d years, %d, weeks, %d days\n");

并打印出来

Expected output: 2 years, 38 weeks, 4 days
Actual output: -127184896 years, -132560896, weeks, -135499072 days

2 个答案:

答案 0 :(得分:3)

您忘记将变量传递给printf。像这样修复最后一行:

printf("Actual output: %d years, %d, weeks, %d days\n", y2, w2, d2);

答案 1 :(得分:-1)

如另一个答案中所述,您需要将值传递给printf

您还需要检查convertTime

的返回值