I have been struggling to understand some pieces of this code. It asks to enter some strings, will count the vowels and display the result. It is some definitions that I don’t understand, the mechanics I do.
In the definitions inside main(). I dont understand what for an argument this ‘(cad)’ is in the entrada function. One line above it is defined an array of 3 pointers to char, namely char *cad[N] if I correctly believe. I would say my problem is everything in the Main function, how the arguments make sense inside the parentheses for the functions. After that I understand alright.
# include<stdio.h>
# include<stdlib.h>
# include<string.h>
# include<ctype.h>
# define N 3
// Function Prototypes
void salida(char *[], int*);
void entrada(char *[]);
int vocales(char *);
int main ()
{
char *cad[N]; // declaring an array of 3 pointers to char
int j, voc[N]; // declaring ints and an array of ints
entrada (cad);// Function to read in strings of characters.
// count how many vowels per line
for (j = 0; j<N; j++)
voc[j] = vocales(cad[j]); // it gets the string and sends it to function vocales to count how many vowels. Returns number to array voc[j]
salida (cad, voc);
}
// Function to read N characters of a string
void entrada(char *cd[] ){
char B[121]; // it just creates an array long enough to hold a line of text
int j, tam;
printf("Enter %d strings of text\n", N );
for (j= 0; j < N; j++){
printf ("Cadena[%d]:", j + 1);
gets(B);
tam = (strlen(B)+1)* sizeof(char); // it counts the number of characters in one line
cd[j] = (char *)malloc (tam); // it allocates dynamically for every line and array index enough space to accommodate that line
strcpy(cd[j], B); // copies the line entered into the array having above previously reserved enough space for that array index
} // so here it has created 3 inputs for each array index and has filled them with the string. Next will be to get the vowels out of it
}
// Now counting the number of vowels in a line
int vocales(char *c){
int k, j;
for(j= k= 0; j<strlen(c); j++)
switch (tolower (*(c+j)))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
k++;
break;
}
return k;
}
// function to print the number of vowels that each line has
void salida(char *cd[], int *v)
{
int j;
puts ("\n\t Displaying strings together with the number of characters");
for (j = 0; j < N; j++)
{
printf("Cadena[%d]: %s has %d vowels \n", j+1, cd[j], v[j]);
}
}
cadis an array of pointers. It only has space for N pointers, not the actual string data. Theentradafunction reads N strings of text. For each of these it allocates some space withmallocand copies the string there.entradasets the corresponding pointer incad(which it sees ascd) to point to the allocated buffer.When you pass an array as an argument, you are not passing a copy. Instead, the address of the first element is passed to the function. This is how
entradacan modify the pointers incad.