How to dynamically allocate a string

1

Well, I wanted to dynamically allocate multiple names in c, I already know how to do just normal but I want to show it here in the code

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

int main(int argc, char** argv)
{
  char *nome;
  nome = (char*)malloc(sizeof(char) * 80); // normal

  char nomes[10][100] // aqui são 10 nomes com 100 caracteres, queira alocar essa parte

   free(nome);
  return 0;
 }
    
asked by anonymous 08.04.2018 / 16:22

1 answer

2

Note that a String is a Vector of Characters, so allocating a String Vector is basically a Character Matrix , to dynamically allocate a Character Matrix you need to do this, specifically for your example 10 names of 100 characters:

char **nomes; //Observe que é um ponteiro para um ponteiro
nomes = malloc(sizeof(char*)*10); //Aqui você aloca 10 ponteiros de char, ou seja, 10 strings **vazias**, ainda **não alocadas**.

Now you need to allocate each of these strings, as follows:

for(indice=0;indice<10;indice++) //Loop para percorrer todos os índices do seu "vetor"
    nomes[indice]=malloc(sizeof(char)*100); //String Dinâmica Normal

From this point you can usually use as if it were a vector of strings, but note that it will be necessary to release each of the allocated allocations, one for the string vector and one for each of the 10 strings, to release all 11 allocations made, like this:

for(indice=0;indice<10;indice++) //Percorre o "Vetor"
    free(nomes[indice]); //Libera a String
free(nomes); //No término do Loop, libera o "Vetor"

In this way there will be no Memory Leak and you will have allocated a dynamic string vector correctly.

    
08.04.2018 / 18:43