【问题标题】:Is it possible to call a local variable from a function to another using pointers是否可以使用指针将局部变量从函数调用到另一个函数
【发布时间】:2015-11-05 01:17:35
【问题描述】:

例如,如果我要使用多个函数进行复杂计算,其中每个函数都完成部分工作,是否可以进行以下操作:

void initialize_equations() {

    int t_constant;
    time_t times;
    double *current_time;
    times= time(NULL);

    t_constant = 365*24*60*60;


    *current_time =times/t_constant;

    printf("%Lf", current_time);
}

int year_day(time_t *crntT, int *constant) {

    int year, month;
    float year_l, month_l;

    year_l=(&current_time)/365; //trying to call crntT from previous function
    year=year_l+1970; //time starts at 1970 therefore turned it from float to int then summed time
    month=((year_l-year)*12)+1; // Month starts at Jan therefore +1

}

【问题讨论】:

  • 为什么不简单地将其声明为全局变量?
  • @David 在代码中声明一个已经是热气腾腾的全局变量会使情况变得更糟。
  • 你不要“调用”变量(除非它们是函数指针,但我们不要去那里)。您“访问”它们。不,你不能那样做。局部变量仅在调用其作用域的函数期间存在。

标签: c pointers time function-pointers


【解决方案1】:

你不能访问在另一个函数中声明的局部变量,不管它是不是在c中的指针。然而,你可以(但也许你不应该)访问在另一个函数中分配的内存,只要你有这个内存块的地址。

例如,如果您使用以下方法为局部变量“current_time”(您没有这样做,但这是另一个问题)分配内存:

double* current_time = (double*) malloc(sizeof(double));

并且您保留已分配内存的地址(该值保存在“current_time”中)。然后,你可以在另一个函数中访问分配的内存,只要你能以某种方式让那个函数知道这个地址。

话虽如此,您为什么不简单地将这个值保存在更高级别的位置,然后将其传递给所有需要该值的函数?

【讨论】:

  • 所以你的意思是我通过了总秒数,以及对年份和日期的引用?
  • 知道我可以用来了解如何做到这一点的任何来源吗?
猜你喜欢
  • 2012-05-21
  • 1970-01-01
  • 2019-07-03
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 2010-10-10
相关资源
最近更新 更多