My test array problem.

Discussion in 'Mac Programming' started by larswik, Dec 23, 2010.

  1. larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    In Short: I am learning array's so I did this test. The goal was to generate a random number from 1-100. Then divided that by 10 so 67 would be 6 as an example. Then with a for loop fill the array with 6 'X''s and then print it delivering 6 X's.

    The code works but it prints 1 more X then it should. I tried to fix this by changing the for loop from i=0 to i=1. But when I do that it stops printing the X's when I run the program?
    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    int main (int argc, const char * argv[]) {
    
    	int guess, toPrint, i, terminate; // my int's
    	char array[11];	//my array
    
    	srand( clock() ); //my random seed
    	
    	guess = (rand() % 100) + 1; // my random num 1-100
    	printf("The random number was %d\n",guess); // test to tell me what num it is
    	
    	toPrint = (guess / 10); // rounds the rand num ie. 67 would be 6
    	printf("The rounded is %d\n",toPrint); //tests to see if the nuber is right
    	
    	terminate = (toPrint + 1); // adding 1 number above my toPrint for array terminate
    	printf("The terminate array num is %d\n",array[terminate]); //Test this number
    	array[terminate] = '\0'; //set my 0 in my array to 1 number higher then toPrint.
    	
    	for(i=0; i<=toPrint; toPrint--){ 
    		array[toPrint] = 'X'; // adds an 'X' to each Char array 
    		printf("The i counter is %d and toPrint is %d\n",i,toPrint); //tests this
    	}
    	printf("%s", array); // prints the X'x
    	printf("\n");
    
        return 0;
    }
    I know the code might look funky and not what you guys would write. But this I understand with what I have learned so far in the book. What am I doing wrong?

    Thanks
     
  2. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #2
    I think I am trying to populate my array backwards and that is my problem. I'm rewriting it a little to fix this and have my for loop use the i counter to increment instead decrementing the toPrint.

    -Lars
     
  3. itickings macrumors 6502a

    itickings

    Joined:
    Apr 14, 2007
    #3
    Since it looks like you're actually interested in learning, I'm just giving you some relevant things to think about...

    Lesson #1
    The two most important thing to remember about arrays is that they begin at 0, and that you must be very careful to not try to use any more positions than is allocated.

    If you allocate an array with char array[3], it will have the positions array[0], array[1] and array[2]. The initial values for array[0], array[1] and array[2] can be totally random. You cannot trust positions that you haven't assigned values.

    Lesson #2
    A standard string is an array of chars, terminated by a zero. It is printed from the character at the first position and onwards, until the zero-terminator is found. If the first position, in this case array[0], contains the terminator, then it doesn't matter what the remaining positions contain.

    When constructing a string of this kind, it is usually a splendid idea to construct it from the first character and onwards, and then making sure that the terminating character is the one following directly after the last character that is to be displayed.

    Lesson #3
    The customary use of for is more like
    Code:
    for (i=0; i<toPrint; i++ )
    or
    Code:
    for (i=0; i<=toPrint; i++ )
    Consider the difference between < and <= in this case, what implications will picking one over the other have? They are both useful, but in different situations.

    Your use of the loop is more like the other common loop, while.
     
  4. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #4
    I solved it, but would like a little clarification. It seems that char array[0] must contain a value or you can't print the %s for the array. By starting to populate from array[1] it was causing the problem and would not print. Is this because array[0] had no value. But when I wrote this code: array[0] = 'x'; then it worked just fine populating from array [1] and up or rewriting the value of array[0] even after I passed the value of 'x' to it.

    So I guess my question is: If a char array has no value assigned to like the beginning of it 'array[0]' but the rest of the array has values assigned to it, is the empty array [0] treated like the array termination, 0?

    the new code:
    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    	
    	int main (int argc, const char * argv[]) {
    		
    		int guess, toPrint, i; // my int's
    		char array[11];	//my array
    		
    		srand( clock() ); //my random seed
    		
    		guess = (rand() % 100) + 1; 
    		printf("The random number was %d\n",guess); 
    		
    		toPrint = (guess / 10); 
    		printf("The rounded is %d\n",toPrint); 
    		
    		array[0] = 'x';
    		
    		for(i=1; i<=toPrint; i++){ 
    			array[i] = 'X'; 
    			printf("The i counter is %d and toPrint is %d\n",i,toPrint); 
    		}
    		array[--i] = 0;
    		
    		printf("%s", array); 
    		printf("\n");
    		
    		return 0;
    	}
     
  5. itickings macrumors 6502a

    itickings

    Joined:
    Apr 14, 2007
    #5
    Sort of. As I wrote in my previous post, unassigned array values are not empty, and you can't trust them. They contain values, just not values set by you. If array[0] happens to contain a termination, then it won't print anything.
     
  6. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #6
    Cool - thanks itickings. we were cross posting and that is what I came up with for my for loop too. The question I was not sure of was if array[0] was left blank, with no value assigned to it, is that also treated as the zero-terminator?

    -Lars
     
  7. ianray macrumors 6502

    Joined:
    Jun 22, 2010
    Location:
    @
    #7
    If by 'left blank' you mean unassigned, then, the value in an unassigned memory location cannot be pre-determined.

    A 'string' is an array of characters which by convention ends with a NUL terminator (ASCII zero, 0, or character literal '\0'). There are other conventions for storing strings (for example Pascal strings) but they are irrelevant here.

    Loops operating over strings typically iterate while the condition "*s" is true -- note that the condition is a contraction of "*s != 0" which may also be written "*s != '\0'".

    Code:
    // gcc -W -Wall print.c
    #include <stdio.h>
    
    void printString(char const* s)
    {
        printf("printf (%s)\n", s);
        printf("loop   (");
        while (*s) {
            putchar(*s++);
        }
        printf(")\n");
    }
    
    int main()
    {
        {
        char const* pointer = "Hello";
        printString(pointer);
        printString(pointer + 1);
        }
    
        {
        char array[2];
        array[0] = '!';
        array[1] = 0;
        printString(array);
        printString(array + 1);
        }
    
        return 0;
    }
    
     

Share This Page