【问题标题】:c++ function with static variable returning next value in array带有静态变量的c ++函数返回数组中的下一个值
【发布时间】:2017-04-08 19:53:57
【问题描述】:

创建一个带有静态变量的函数,该变量是一个指针(默认参数为零)。当调用者为此参数提供值时,它用于指向 int 数组的开头。如果您使用零参数调用函数(使用默认参数),函数将返回数组中的下一个值,直到它在数组中看到“-1”值(充当数组结尾(指示符) ). 在 main() 中执行这个函数。

这是我所拥有的:

int pr(int *p = 0) {
    static int* po =0 ;
    if (p) {
        po = p;
        return *po;
    }
    else {
        return -1;
    }

    if (*p == -1) {
        return -1;
    }
    return *po++;    
}

int ar[] = {2,5,1,2,6,-1};

int main() {

    pr(ar);

    int pl;
    pl = pr();
    while (pl != -1) {
        cout << pl << endl;
        pl = pr();
    }
}

当我启动它时,什么都没有打印出来,我不知道为什么。有什么帮助吗?

【问题讨论】:

  • 如果函数参数不为零,它的用途是什么?
  • @KerrekSB 初始化静态变量
  • 好的。对于所有情况,该函数返回什么?

标签: c function pointers static


【解决方案1】:

您也需要保留下一个数组索引:

int f(int* a = NULL) {
  static int* arr = NULL;    // internal state ...
  static int idx = 0;        // ...in these two vars

  // Reset the internal state if a new array is given
  if (a != NULL) {
    arr = a;
    idx = 0;
  }

  // #1
  if (arr == NULL || arr[idx] == -1) { return -1; }

  return arr[idx++];
}

我对标记为#1 的问题中未指定的部分做了一些假设。如果还没有提供指针,或者之前已经到达数组末尾,我们每次只返回-1

【讨论】:

    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 2023-03-18
    • 2011-11-12
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    相关资源
    最近更新 更多