c - 提示编写可重入求和函数

标签 c linux pointers reentrancy

我必须用 C 语言编写一个普通的求和函数和一个可重入函数。我必须传递一个 int 并且必须将它添加到 INIT_VALUE 中。在可重入函数中,main 传递一个 int* 来保持状态。如何在第一次调用时初始化该指针?我必须在乐趣中初始化它,而不是在主要中。谢谢

#include <stdio.h>
#ifndef INIT_VALUE
#define INIT_VALUE 0
#endif

int somma(int x){
    static int val = INIT_VALUE;
    val += x;
    return val;
}

int somma_r(int x, int* saveptr){
    // pointer initialize and sum
    // return old_value ;
}

int main (){
int x;
int s;
int s_r;
int *stato;
fscanf(stdin,"%d",&x);
while(x>=0){
    s = somma(x);
    s_r = somma_r(x,stato);
       fscanf(stdin,"%d",&x);
   }
   printf("%d\n",s);
   printf("%d\n",s_r);
   return 0;
}

最佳答案

使用程序中的函数签名 (int somma_r(int x, int* saveptr)),您无法在第一次调用时初始化指针。

您可能需要这个(修改了 3 行代码):

...
int s   = INIT_VALUE;     // otherwise s will not be initialized
int s_r = INIT_VALUE;     // otherwise s_r will not be initialized
int stato = INIT_VALUE;   // state to be used with the somma_r function
    ...
    s_r = somma_r(x, &stato);
    ...

somma_r函数

int somma_r(int x, int* saveptr){
  *saveptr += x;
  return *saveptr;
}

somma_r 函数内进行初始化的版本。这需要修改 somma_r 的签名:

int somma_r(int x, int **saveptr){
  if (*saveptr == NULL) {
    *saveptr = malloc(sizeof(int));
    **saveptr = INIT_VALUE;
  }

  **saveptr += x;
  return **saveptr;
}    

int main (){
  int x;
  int s = 0;
  int s_r = 0;
  int *stato = NULL;
  fscanf(stdin,"%d",&x);

  while(x>=0){
    s = somma(x);
    s_r = somma_r(x,&stato);
    fscanf(stdin,"%d",&x);
  }

  printf("%d\n",s);
  printf("%d\n",s_r);
  return 0;
}

关于c - 提示编写可重入求和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35941267/

相关文章:

c - 在堆栈或堆上初始化结构?

c - C DLL 目录中的加载时动态链接

linux - 用文件名 linux 的一部分替换文件中的列

c# - 如何使用 Mono 从 Linux 中的网络摄像头捕获?

c++ - Caffe源码中层函数头中指针运算符的含义

c - 方括号内的指针?

c - 仅映射文件 C 的第一个字母

c - 如何在 C 中查找二进制文件的完整路径名?

linux - 生成文件 :1: *** missing separator. 停止

pointers - 类型声明的 Fortran 指针属性