'Hello , I think I have a problem with the pointers , I need help ! , can you fix my code
#include <stdio.h>
void chercherVal(int tab[], int N, int A, int *pos, int *nb_occ) {
int i = 0;
while (i < N) {
if (tab[i] == A) {
*pos = i;
*nb_occ = *nb_occ + 1;
}
i++;
}
printf("la position est %d et le nombre d'occurence est %d", pos, nb_occ);
}
int main() {
int pos = -1, nb_occ = 0;
char A;
int i, N;
int tab[100];
printf("saisir le nombre d'elements de tab :");
scanf("%d", &N);
for (i = 0; i < N; i++) {
printf("saisir l'element %d du tableau tab :", i + 1);
scanf("%d", &tab[i]);
}
printf("saisir la valeur a rechercher :");
scanf("%s", &A);
chercherVal(tab, N, A, &pos, &nb_occ);
}
Solution 1:[1]
Here is one pointer problem (or lack of)
printf("la position est %d et le nombre d'occurence est %d", pos, nb_occ);
should be
printf("la position est %d et le nombre d'occurence est %d", *pos, *nb_occ);
The compiler should have warned that the wrong argument types are being passed.
Solution 2:[2]
Reading a string with scanf("%s", &A); into a single char has undefined behavior because scanf() will store the bytes and a null terminator, writing beyond the destination variable.
You should either make A and int and read a number: scanf("%d", &A);
Or you should read a single char with scanf(" %c", &A); (note the space before the % to skip pending white space, including the newline left in the standard input by previous calls to scanf().
Here is a modified version:
#include <stdio.h>
void chercherVal(const int tab[], int N, int A, int *posp, int *nb_occp) {
int pos = -1, occ = 0;
for (int i = 0; i < N; i++) {
if (tab[i] == A) {
occ++;
if (pos < 0) { /* only store the first position */
pos = i;
}
}
}
/* always store the return values */
*posp = pos;
*nb_occp = occ;
}
int main() {
int tab[100];
int N, A, pos, nb_occ;
printf("saisir le nombre d'elements de tab : ");
if (scanf("%d", &N) != 1)
return 1;
if (N > 100) /* prevent buffer overflow */
N = 100;
for (int i = 0; i < N; i++) {
printf("saisir l'element %d du tableau tab : ", i + 1);
if (scanf("%d", &tab[i]) != 1)
return 1;
}
printf("saisir la valeur a rechercher : ");
if (scanf("%d", &A) != 1)
return 1;
chercherVal(tab, N, A, &pos, &nb_occ);
printf("la position est %d et le nombre d'occurences est %d\n", pos, nb_occ);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Weather Vane |
| Solution 2 |
