Thread: Am I missing something? (2d arrays)

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    16

    Am I missing something? (2d arrays)

    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.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    for ( j=0; j<y-1; j++ )
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    16
    Wow, I am an idiot....

    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-25-2009, 09:29 PM
  2. 2D arrays with variable indexes
    By homeyg in forum C++ Programming
    Replies: 13
    Last Post: 01-22-2005, 10:40 PM
  3. 2D Arrays: Column/Row Order
    By Ashes999 in forum C++ Programming
    Replies: 1
    Last Post: 07-01-2003, 08:03 PM
  4. 2d arrays: H e l p!
    By scuba22 in forum C++ Programming
    Replies: 4
    Last Post: 11-04-2002, 05:54 PM
  5. how can i pass 2d arrays
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 11-02-2001, 07:33 AM