Problem when declaring a string to a variable in a C structure

1

I am doing some C test programs to learn a little more about the language, the program I am doing now is to show the grades of some students:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct alumno{
    char name[21];
    int edad;
    int promedio;

}alumnos[50];
int main(){
    srand (time(NULL)); 
    int cantidad, i, n;
    char names[7][10] = {"Juan", "Max", "Julia", "Pablo", "Alejandra", "Regina", "Angel"};
    char lstnames[5][10] = {"Perez", "Gonzales", "Martinez", "Rodriguez", "Contreras"};
    printf("Ingrese la cantidad de alumnos: ");scanf("%i", &cantidad);
    for(i=0;i<cantidad-1;i++){
       alumnos[i].name = "%s %s",names[rand()%8], lstnames[rand()%6];
       alumnos[i].edad = rand() % 12 + 19;
       alumnos[i].promedio = rand() % 11;
       printf("\n----------\nNombre: %s\nEdad: %i\nPromedio: %i\n",alumnos[i].name, alumnos[i].edad,alumnos[i].promedio); 
        }
       return 0;
   }

This is the error message that appears to me:

5.c: En la funci¾n 'main':
5.c:17:19: error: assignment to expression with array type
alumnos[i].name = "%s %s",names[rand()%8], lstnames[rand()%6];
                ^
    
asked by binario_newbie 08.10.2018 в 00:40
source

2 answers

1

This:

"%s %s",names[rand()%8], lstnames[rand()%6];

may make sense as arguments for some functions , for example printf( ) , but not in isolation; the C language does not provide that kind of primitives to work with strings of characters.

If you want to generate a text string from a format string and certain arguments, saving the content in a specific memory position, the functions to use are sprintf( ) or snprintf( ) :

  

The functions in the printf () family produces output according to a format
  ...
sprintf( ) and snprintf( ) write to the character string str.

Generally speaking, it is preferable to use snprintf( ) , since it limits the total of printed characters to a maximum. This way we avoid passing problems of assigned memory zones:

for( i = 0; i < cantidad - 1; i++ ) {
  snprintf( &( alumnos[i].name ), sizeof( alumnos[i].name ), "%s %s",names[rand( ) % 8], lstnames[rand( ) % 6] );
  alumnos[i].edad = rand( ) % 12 + 19;
  alumnos[i].promedio = rand( ) % 11;
  printf("\n----------\nNombre: %s\nEdad: %i\nPromedio: %i\n",alumnos[i].name, alumnos[i].edad,alumnos[i].promedio); 
}
    
answered by 08.10.2018 / 01:46
source
0

Start by removing the amount-1 and leave amount, "so you do not go the clamp", char name [21] students [i] .name [? ¿] = if name is a * []? that with that *** you can

;)

   char aleatorio[21];
   strcpy(aleatorio,names[rand()%7]);
   strcat(aleatorio, " ");
   strcat(aleatorio,lstnames[rand()%5]);

   strcpy(alumnos[i].name,  aleatorio);
answered by 08.10.2018 в 01:38