I would like to know what the [i] is for and why my table is not displayed if I do not put it, thank you !
#include <stdio.h>
void affiche(int* tableau, int taille);
int main()
{
int tableau[5] = { 12,15,50,20 };
affiche(tableau, 4);
return 0;
}
void affiche(int *tableau,int taille)
{
int i;
for (i = 0; i < taille; i )`
{
printf("%d\n", tableau[i]);
}
}
CodePudding user response:
[i]
is the C language syntax for array notation.
tableau
is an array of 5 integers.
int tableau[5] = {12,15,50,20}
In memory tableau has 5 slots allocated to it due to the above declaration.
Slots 0 through 4 are your initialization values. Slot 5 is uninitialized (though modern c compilers might set this value to null or zero (0).
tableau
-----------------------
index | 0 | 1 | 2 | 3 | 4 |
-----------------------
value | 12 | 15 | 50 | 20 | ? |
-----------------------
inside function affiche(...)
this statement
printf("%d\n", tableau)
tries to print to console a single integer (%d) followed by a newline (\n)
But tableau
is an array of 5 integers.
So you need the array index to select a specific integer individually like this:
printf("%d\n", tableau[0]) // output: 12
printf("%d\n", tableau[1]) // output: 15
printf("%d\n", tableau[2]) // output: 50
printf("%d\n", tableau[3]) // output: 20
printf("%d\n", tableau[4]) // output: unknown, possible exception
or by function call to affiche(tableau, 4);
which ends at index 3
void affiche( int *tableau, int taille)
{
int i;
for( i = 0; i < taille; i ){
printf( "%d\n", tableau[i] );
}
}
Which outputs:
12
15
50
20