2016-03-11 3 views
-1

Je dois écrire une fonction de somme normale et une fonction réentrante en C. Je dois passer un int et il doit être ajouté à un INIT_VALUE. Dans la fonction réentrante, le principal passe un int * pour conserver l'état. Comment puis-je initialiser ce pointeur sur le premier appel? Je dois l'initialiser dans le plaisir, pas dans le principal. MerciIndice écrire une fonction de somme réentrante

#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; 
} 
+0

Je dois l'initialiser dans le plaisir, pas dans le main_. Non pourquoi? –

+0

Utilisez un pointeur vers un pointeur et utilisez [malloc] (http://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm) dans votre func. Par exemple. 'int somma_r (int x, int ** saveptr) {* saveptr = malloc (sizeof (int);}' – LPs

Répondre

2

Avec la signature de fonction dans votre programme (int somma_r(int x, int* saveptr)) vous ne pouvez pas initialiser le pointeur sur le premier appel.

Vous devez probablement ce (3 lignes de votre code modifié):

... 
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); 
    ... 

fonction somma_r

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

version avec initialisation dans la fonction somma_r. Cela nécessite une modification de la signature de 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; 
} 
+0

Je ne peux pas résister: [Dois-je lancer malloc retour?] (http://stackoverflow.com/questions/605845 /do-i-cast-the-result-of-malloc) Je blague ...;) – LPs

+0

@LPs correct, j'utilise le compilateur C++ ... –

+0

;) Oui de la malédiction. J'ai lu (si je ne me trompe pas) votre discussion avec Olaf il y a quelque temps. – LPs