Hi, as part of a larger program I need to create a list of random words(user defined, both the number of words and the length of each word), display the list, and then write valid words to a file. I'm stuck at creating and displaying the list correctly. Here is the snippet of code that is troubling me:
Code:
void generate_words( unsigned long int words, int length ) {
unsigned long int x;
int y,r,i,j;
srand( time(NULL) );
x = (int) ( rand() / ( RAND_MAX / words + 1 )) + 1;
y = (int) ( rand() / ( RAND_MAX / length + 1 )) + 1;
char buffer[x][y];
////////////Problem begins here.///////////////////////
for( i=0; i<x; i++ ) {
for( j=0; j<y; j++ ) {
r = rand()%25;
buffer[i][j] = letters[r];
}
printf("i=%d, j=%d\n", i, j );
buffer[i][j] = '\0';
}
int k;
for( k=0; k<x; k++ ) {
printf( "buffer[%d] = %s\n", k, buffer[k] );
}
for( i=0; i<x; i++ ) {
for( j=0; j<=y; j++ ) {
printf("buffer[%d][%d] = %c\n", i,j,buffer[i][j]);
}
}
printf("x = %d, y = %d\n", x, y );
}
The problem is each randomly generated string isn't null terminated, so when I print the buffer array it prints every character. It looks to me like I'm null terminated in the line
Code:
buffer[i][j] = '\0';
But that obviously isn't what I need to be doing. Any help would be greatly appreciated.