Good evening community, I continue in my battles with the language c
, yesterday in allocating memory to an array of integers, but today I have come across the need to work with an Array of strings. The exercise consists of creating an array of N
positions where names that must be entered by the console are stored, the code I have made is the following:
int numeroEmpleados = 0;
char *empleados = NULL;
void inicializarEstructuras();
void llenadoDeDatos();
int main(){
inicializarEstructuras();
llenadoDeDatos();
imprimirDatos();
return 0;
}
void inicializarEstructuras(){
printf("Ingrese la cantidad de empleados: ");
scanf("%d", &numeroEmpleados);
//Reserva de memoria para los vectores y matrices
empleados = (char*)malloc(numeroEmpleados*sizeof(char));
}
void llenadoDeDatos(){
//Se solicitan los nombres de los empleados
for(int i = 0; i < numeroEmpleados; i++){
printf("Ingrese el nombre para el empleado [ %d ]: ", i + 1);
scanf("%s", &empleados[i]);
}
}
void imprimirDatos(){
for(int i = 0; i < numeroEmpleados; i++){
printf("empleado %s", empleados[i]);
printf("\n");
}
}
However the code compiles withwarnings
empresa.cpp: In function ‘void imprimirDatos()’:
empresa.cpp:75:37: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat=]
printf("empleado %s", empleados[i]);
And when executing the program, an error occurs segmentation fault
when storing some of the names entered.
The exercise is academic but it has given me ball all afternoon. Thank you
Well, I tell you that after messing around the network and making a finite number of changes to my code I have solved it, although I am missing a part (it is not very important for the exercise) I have already been able to store and read an array of strings
The changes I made were the following:
Declare the array as an array
The memory reservation in the same way
And when reading the input names, I reserve memory for the position where the entered name is going to be saved
This is where I have the pending, how to make the reserved size not be fixed
(10)
but that it is dimensioned according to the number of characters entered by the user.The complete code is below:
You can use
strlen
andstrcpy
in the following way:In this particular implementation you will still be limited by the 30 characters that are
nombre_empleado_temp
however this array will exist temporarily as it is an automatic variable defined in the functionllenadoDeDatos()
Answering the doubt of your own answer :
You can choose, as @MarcoRamírez has told you , to use a buffer of sufficient size to cover your needs:
If that doesn't satisfy your craving for precision because you think it might still fall short, you can choose to read the sequence in chunks and allocate memory accordingly:
The last reserve is made to exactly adjust the size of the reserve so as not to waste any bytes... since we get picky we go all the way.