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;
}
-std=c99option in GCC.iout offor(int i=0;i<len;i++)srand(time(NULL));should be near the start ofmainand called only once, but since you only callgenerate_stringonce, that won't matter here.temp[i+1]='\0';should betemp[i]='\0';because the loop ends withiincremented. Your array is broken. Even without that mistake, the array is too short to hold the terminator, trychar temp[numOfChars+1];