How to make dynamic string allocation

Asked

Viewed 5,093 times

1

Well I wanted to dynamically allocate several names in c, I already know how to do only normal but want as I show 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;
 }

1 answer

3


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

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 use normally, as if it were an array of strings, but note that it will be necessary to release each of the made allocations, one for the array of strings and one for each of the 10 strings, so you will have to release all 11 made allocations, in this way:

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"

That way there won’t be any Memory Leak and you will have allocated a dynamic string array correctly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.