Chain Arrangements

0

How can I store strings in a C array? For example I want an arrangement where I can save 3 names

arrangement="juan", "Pedro", "Santiago";

juan in position 0 of the arrangement Pedro in position 1 of the arrangement Santiago in position 2 of the settlement

    
asked by Fr13nds 30.11.2018 в 03:03
source

2 answers

1

define an array in the following way

char *arreglo[]={"Juan","Pedro","Santiago"}; 

is an array of pointers to Strings. To print the contents of each element of the array you should do, for example:

printf("Es %s", *arreglo[0]); //Es Juan
printf("Es %s", *arreglo[1]); //Es Pedro
printf("Es %s", *arreglo[2]); //Es Santiago

If you put only:

arreglo[0]; 

will show you the memory address where the pointer to that string is stored, which value, I suppose, does not interest you.

    
answered by 30.11.2018 / 03:09
source
1

Hi possibility is to use an array of structures, where the structure, in turn, has a field that is an array, in this case the "name" field.

This solution is appropriate if there are other data associated with the person, such as ID or telephone. These data will be new fields of the persona_s structure

#include <stdio.h>
#include <string.h>

//Crea el tipo de dato "persona_s"
struct persona_s
{
    char nombre[30] ;
};

int main()
{
    //Crea la estructura de tipo persona    
    struct persona_s arreglo[3];

    //Escribe el campo nombre con los valores desados
    strcpy (arreglo[0].nombre, "Juan");
    strcpy (arreglo[1].nombre, "Pedro");
    strcpy (arreglo[2].nombre, "Santiago");

    //Imprime el contenido del campo nombre
    for (int i = 0 ; i<3 ; i++)
    {
        printf("Nombre: %s\n",arreglo[i].nombre);
    }
    return 0 ;
}
    
answered by 30.11.2018 в 15:33