Exercice langage C: Fonctions et pointeurs

Exercice langage C
[tab name=’Exercice langage C’]

Créez un nouveau programme, auquel vous ajouterez la fonction suivante:

1
2
3
void fonction1(int *p, int v) {
     *p = v;
   }
  1. Effectuez un appel à fonction1 dans la fonction main. Faites-le de manière à comprendre ce que fait fonction1.
  2. Ecrivez une fonction
1
2
void echange(int *p1, int *p2) {
      }

qui échange le contenu de p1 et p2 sans utiliser d’affectation avec ces variables, mais en se servant de fonction1.

3. Testez votre fonction echange en l’appelant dans main.

[/tab][tab name=’Correction’]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include
 
using namespace std;
 
void fonction1(int *p, int v) {
  *p = v;
}
 
void echange(int *p1, int *p2) {
  int t;
  fonction1(&t, *p1);
  fonction1(p1, *p2);
  fonction1(p2, t);
}
 
int main(int argc, char **argv) {
  int i = 5;
  int j = 9;
 
  echange(&i, &j);
 
  cout << "i = " << i << ", j = " << j << endl;
 
  return 0;
}

Exercice langage C

Cours gratuit, Cours informatique, Télécharger cours, Exercice gratuit, Exercice langage C

[/tab][end_tabset skin= »lightness » ]

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Besoin d'aide ?