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

标签 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

最佳答案

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

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

关于c - 为什么我会得到这些随机值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26351337/

相关文章:

c - 使用 Lucas-Lehmer 素性检验的 Mersenne 素数

python - 如何更有效地触发类内部函数?

c++ - C++中的指针同一个变量有两个不同的地址

c - 为什么 fun(int *p) 不改变指针的值?

c - 使用套接字的自编码下载管理器下载后截断的 tar.gz 存档

c - "Repassing"函数参数

调用结构类型的函数并返回指针不运行

c++ - 将复杂对象传递给 C++ 中的函数,但数组订阅运算符无法正常工作

c - 将新数据读取到函数内的指针参数中?

c++ - 函数需要参数并返回指向 void 函数的指针