Arrays

This is a discussion on Arrays within the C++ Programming forums, part of the General Programming Boards category; why does my second loop (for a....) not return pupil[0] it will only start from pupil[1] Code: #include <iostream> #include ...

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    14

    Arrays

    why does my second loop (for a....) not return pupil[0] it will only start from pupil[1]

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(){
        char *pupil[10]= {
    	"Ben",
    	"Graham", 
    	"Joe", 
    	"James", 
    	"Tom",
    	"Tim"};
    	char house[]= {0,6};
    	char clss[]= {0,6};
    	char game1[]= {0,6};
    	char game2[]= {0,6};
    	char game3[]= {0,6};
    	char game4[]= {0,6};
    	char ingame[]= {0,6};
    	char x;
    	int b=1;
    		for(int i = 0;i <= 5; i++){
    			cout<<i;
    			cout<<"Enter house for : "<<pupil[i]<<endl;
    			cin>>x;
    			house[i]=x;
    		}
    		
    		for(int a = 0;a <= 5;a++){
    			cout<<pupil[a]<<endl;
    			cout<<house[a]<<endl;
    		}
    
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    The way you declared your house, clss, and game arrays, the size of the array is determined by the number of entries in the list. Each of those lists have two entries, so each of those arrays has two elements the first initialized to the character with the code 0, the second initialized with the character with the code 6. What you probably meant to do was:
    Code:
    char house[6];
    Later your first loop writes to house past its bounds which causes undefined behavior- meaning anything can happen like the error you experienced, a crash or some other problem.

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    14
    aaah yes lol that would explain alot.....thats the narrowed down version of wat im doing and may explain the rest of the weird behaviour!

    thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. Need Help With 3 Parallel Arrays Selction Sort
    By slickwilly440 in forum C++ Programming
    Replies: 4
    Last Post: 11-19-2005, 10:47 PM
  4. Building B-Tree from Arrays
    By 0rion in forum C Programming
    Replies: 1
    Last Post: 04-09-2005, 03:34 AM
  5. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 09:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21