如何在函数中重置静态变量 [英] How to reset static variables within a function

查看:216
本文介绍了如何在函数中重置静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法重置在函数内声明为静态的变量?目的是确保不使用不相关调用中的剩余值来调用该函数.例如,我在矩阵的列上有一个函数.

Is there a way to reset variables declared as static within a function? The goal is to make sure that the function is not called with lingering values from an unrelated call. For example, I have a function opearting on columns of a matrix.

int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows 
   if (column != whichColumn){
    memset(v,0,size);
    whichColumn = which;
   } 
   //do other things
}

该函数被调用n次,每列一次.这是重置"静态变量的正确方法吗?还有其他通用的简单方法来重置静态变量吗?例如,我要确保如果使用可能具有不同维数的新矩阵进行调用,则将向量v调整大小并清零等.似乎最简单的方法可能是使用NULL指针调用函数:

The function is called n times, once for each column. Is this a proper way of "re-setting" the static variable? Are there other general fool-proof ways of resetting static variables? For example, I want to make sure that if the call is made with a new matrix with possibly different dimensions then the vector v is resized and zeroed etc. It seems the easiest way may be to call the function with a NULL pointer:

int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows 
   if (A == NULL){
    FREE(v);
    whichColumn = 0;
   } 
   //do other things
}

推荐答案

我建议将其转换为结构,并编写一个小的辅助函数来管理您要执行的操作的语义.如果请求适合其大小,它可以返回缓冲区,或者根据需要创建一个新的缓冲区(并释放旧的缓冲区).

I'd recommend turning it into a struct and writing a small helper function for managing the semantics of what you're trying to do. It could return the buffer if the request is appropriate for its size, or create a new one on demand (and free the old one) if necessary.

这篇关于如何在函数中重置静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆