How to store value of a function that returns a char pointer in a string vector

0

I would like to know how I can store the return of the function below, which generates a random string, into a vector of strings with 100 of those words generated by the function, then to do an ascending and descending ordering in the vector.

char* geraStringAleatoria(){

char *validchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *novastr;
register int i;
int str_len;

// novo tamanho
str_len = (rand() % MAX_STR_SIZE );

// checa tamanho
str_len += ( str_len < MIN_STR_SIZE ) ? MIN_STR_SIZE : 0;

// aloca memoria
novastr = ( char * ) malloc ( (str_len + 1) * sizeof(char));
if ( !novastr ){
    printf("[*] Erro ao alocar memoria.\n" );
    exit ( EXIT_FAILURE );
}

// gera string aleatória
for ( i = 0; i < str_len; i++ ) {
    novastr[i] = validchars[ rand() % strlen(validchars) ];
    novastr[i + 1] = 0x0;
}

   return novastr;
}

In the main function I can assign the function return to a string:

int main() {
    char *str;
    str = geraStringAleatoria();

   return 0;
}

But I do not know how to store each word generated in a string vector, as if each vector position were a word.

    
asked by anonymous 18.01.2018 / 19:04

1 answer

2

So - what you need to have there in your main function is a vector of pointers to strings: each position in the vector will actually contain the address of a string.

In this way, each position in your vector points to a string in a position other than memory. Subsequently, your sorting function (s) will only need to change the values that are in that place structure - the strings will continue where they are created.

You can either have a fixed maximum size vector declared in the program:

main () {
   char * dados[100]; 
} 

How can you use declare simply that it is a pointer to pointers, and allocate memory dynamically:

main () {
  char ** dados;
  int tamanho;
  tamanho = ... // obtem o tamanho de alguma fonte externa
  dados = malloc(tamanho * sizeof(char *));

}

In both cases, just looping by calling your geraStringAleatoria function, and with each call put the returned pointer in a different position in that structure.

main () {
  ...
  for (i = 0; i < tamanho; i++) {
    dados[i] = geraStringAleatoria();
  }
  ...
}

Always keep in mind that C has no strings - they work almost like a string, but all are actually a sequence of bytes in a memory address - and whenever we pass or return a string like parameter, we are actually passing and retrieving this address (pointer)

    
18.01.2018 / 20:43