Storing Strings in Vectors - C

2

How do I store more than one name in a variable of type char , why put it, let's assume name [20] , I'm defining that it has received 20 characters, not that it can receive 20 elements, the code I'm trying to test, that's it here.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>


int i;
float tvendas[10], pvendas[10];
char nome[15];

int main(void){

    setlocale(LC_ALL, "Portuguese");

    for(i=0; i<=9; i++)
    {

        printf("%d° VENDEDOR | DIGITE O TOTAL DE VENDAS: R$ ", i+1);
        scanf("%f", &tvendas[i]);

        printf("%d° VENDEDOR | DIGITE O PERCENTUAL DE AUMENTO DAS VENDAS: ", i+1);
        scanf("%f", &pvendas[i]);

        printf("%d° VENDEDOR | DIGITE O NOME: ", i+1);
        scanf("%s", nome[i]);  // MEU PROBLEMA É AQUI

    }

    for(i=0; i<=9; i++){
    printf("TESTE %s\n", nome[i]); //TESTANDO PARA VER SE OS NOMES APARECEM.
    }

return 0;
}
    
asked by anonymous 31.10.2018 / 16:42

2 answers

3

You can make a two-dimensional array:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>


int i;
float tvendas[10], pvendas[10];
char nome[15][15];

int main(void){

    setlocale(LC_ALL, "Portuguese");

    for(i=0; i<=9; i++)
    {

        printf("%d° VENDEDOR | DIGITE O TOTAL DE VENDAS: R$ ", i+1);
        scanf("%f", &tvendas[i]);

        printf("%d° VENDEDOR | DIGITE O PERCENTUAL DE AUMENTO DAS VENDAS: ", i+1);
        scanf("%f", &pvendas[i]);

        printf("%d° VENDEDOR | DIGITE O NOME: ", i+1);
        scanf("%s", nome[i]);  // MEU PROBLEMA É AQUI

    }

    for(i=0; i<=9; i++){
    printf("TESTE %s\n", nome[i]); //TESTANDO PARA VER SE OS NOMES APARECEM.
    }

return 0;
}
    
31.10.2018 / 17:39
4

To show another alternative, and to some extent as a complement to @aa_sp's response, you can also use an array of pointers to char . In this scenario it is necessary to allocate each name individually in for before using.

//...
char *nome[15]; //vetor de ponteiros para char (strings), 15 nomes

int main(void){
    //...
    for(i=0; i<=9; i++){
        //...
        nome[i] = malloc(sizeof(char) * 30); //aloca espaço uma string de 29 carateres
        scanf("%s", nome[i]); //scanf igual ao que tinha
    }

    for(i=0; i<=9; i++){
        printf("TESTE %s\n", nome[i]); //printf também igual ao que tinha
    }
    //...

For the example you have, the solution to allocate in stack as the @aa_sp answer showed is preferable because it is faster, simpler and avoids having to free memory when you no longer need the strings .

This form I've shown is useful in at least two scenarios:

  • When you create strings in a function and you need them to exist beyond the lifetime of the function
  • If you want the placeholder for each name to be different.
  • As a final note, I used sizeof(char) only to make it clear that it is the size of the char that is supporting malloc even though it is guaranteed to always result in 1 .

        
    31.10.2018 / 20:22