I need to create a function that is given a table with different phrases and I must print the first phrase on the table that ends in "n". How would I go about this?
So far I have the table with three phrases with the second one ending in "n". Ive tried different things for the last hour but I'm new to C and it is tricky.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char TTablaFrases[5][80]; //una tabla de 10 frases
int FraseAcabadaEnN (TTablaFrases tabla)
{
}
int main(void) {
TTablaFrases miTabla;
strcpy (miTabla[0], "First phrase");
strcpy (miTabla[1], "Second phrase n");
strcpy (miTabla[2], "Third phrase");
}
CodePudding user response:
If ends in 'n' means the last letter than this would do.
char TTablaFrases[5][80]
degrades to a char *TTablaFrases[80]
when passed to a function, so you need to pass in the length of your table or use a sentinel (empty string aka '\0') to signify end of the table.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char TTablaFrases[5][80]; //una tabla de 10 frases
int FraseAcabadaEnN(TTablaFrases tabla) {
for(size_t i = 0; *tabla[i]; i ) {
size_t l = strlen(tabla[i]);
if(tabla[i][l-1] == 'n')
return i;
}
return -1;
}
int main(void) {
TTablaFrases miTabla;
strcpy(miTabla[0], "First phrase");
strcpy(miTabla[1], "Second phrase n");
strcpy(miTabla[2], "Third phrase");
miTabla[3][0] = '\0';
int i = FraseAcabadaEnN(miTabla);
if(i >= 0)
printf("%s\n", miTabla[i]);
}
and it prints:
Second phrase n
CodePudding user response:
The function needs to loop over each row of the array, skipping rows that contain no information. For rows that contain text, the last character is tested as being the letter 'n'. The index of the first row that meets this criteria is returned to the caller, else an impossible value is returned to indicate no rows matched the criteria.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// incorrect comments are disturbing
typedef char TTablaFrases[5][80]; // una tabla de frases
int FraseAcabadaEnN( TTablaFrases tabla ) {
// check each 'entry'
for( size_t i = 0; i < sizeof *tabla/sizeof *tabla[0]; i )
// is there something to check on this entry?
if( tabla[i][0] )
// is the last character 'n'?
if( tabla[i][ strlen( tabla[i] ) - 1 ] == 'n' )
// return this table index
return i;
// return impossible 'index' indicating "not found"
return -1;
}
int main() {
TTablaFrases miTabla = { 0 }; // ALWAYS intialise ALL variables
strcpy( miTabla[0], "First phrase" );
strcpy( miTabla[3], "Second phrase n" ); // NOTE! putting into array element #3
strcpy( miTabla[2], "Third phrase" );
int i = FraseAcabadaEnN( miTabla );
if( i >= 0 )
printf( "Elem #%d - %s\n", i, miTabla[i] );
return 0;
}
Output
Elem #3 - Second phrase n
ALWAYS initialise variables. Uninitialised variables are a source of many bugs.