0

Random string generator using C programming. How to fix "for loop initial declaration used outside c99 mode"?

void generate_string(char **string){

    srand(time(NULL));
    int numOfChars=rand()%9+1;
    int i=0;
    char temp[numOfChars];
     for(i=0;i<numOfChars;i++){
        char tmp ='A'+rand()%26;
        temp[i]=tmp;

     }
     temp[i+1]='\0';
    strcpy(*string,temp);
}


    int main()
    {
    char *str;
    str= (char*)malloc(11 * sizeof(char));
    generate_string(&str);
    int len=(int)strlen(str);
        printf("Random String:");
    for(int i=0;i<len;i++) { 
        printf("%c",*str);
        str++;
       } 
    return 0;
}
4
  • 2
    Compile with -std=c99 option in GCC. Commented Mar 9, 2017 at 19:56
  • 3
    or move the definition of i out of for(int i=0;i<len;i++) Commented Mar 9, 2017 at 19:57
  • In general, srand(time(NULL)); should be near the start of main and called only once, but since you only call generate_string once, that won't matter here. Commented Mar 9, 2017 at 19:57
  • temp[i+1]='\0'; should be temp[i]='\0'; because the loop ends with i incremented. Your array is broken. Even without that mistake, the array is too short to hold the terminator, try char temp[numOfChars+1]; Commented Mar 9, 2017 at 20:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.