0

I'm having a problem with a function meant to insert random C-strings into an array. I've read a few other questions about this on stackexchange, but none seem to work for me.

void rand(const char *tab[], int n){
    int i, j;
    char c[10];
    for(i=0; i<n; i++){
        for(j=0; j<10; j++){
            c[j]= rand()%26 + 97;
        }
        tab[i]=c;
    }
}

When trying to print it out, I get a blank screen, as if the array is empty. I declared the array as const char *tab[] and use the function rand(tab, 5). What could be wrong?

photons3432
  • 5
  • 1
  • 9

1 Answers1

0

you need to make a copy of the generated string. and you need a string terminator

void rand(const char *tab[], int n){
    int i, j;
    char c[10];
    for(i=0; i<n; i++){
        for(j=0; j<9; j++){
            c[j]= rand()%26 + 97;
        }
      c[9] = '\0';
        tab[i]=strdup(c) <<<<=====
    }
}

the strings are allocated on the heap - free them when you are finised

for(int i=0; i < NO_STRINGS; i++)
{
   free(tab[i]);
}
pm100
  • 48,078
  • 23
  • 82
  • 145