Thread: 2D Arrays

  1. #1
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798

    2D Arrays

    This might be a really stupid question that I will kick myself for not knowing the answer but why, from the output of this program is the first number 4 times the second number?

    Code:
    #include <iostream.h>
    
    
    int main()
    {
    	const int sizea(5), sizeb(5);
    	int a[sizea][sizeb];
    
    	
    	for (int i=0;i<=sizea-1;i++)
    	{
    		for (int o=0;o<=sizeb-1;o++)
    		{
    			a[i][o]=1;
    		}
    	}
    	
    		cout<<sizeof(a)<<endl;
    		cout<<(sizea*sizeb)<<endl;
    		return 0;
    }

  2. #2
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Because sizeof(a) = sizeof(int) * sizea * sizeb = 4 * 5 * 5
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  3. #3
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798
    Yeah, you're right, thanks. I'm having one of those dumb days!!

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    the operator sizeof() returns the number of bytes in a particular variable, not the number of elements in the array you are using it on. To get the number of elements that could be stored in the array called a using the sizeof() operator use the following syntax: sizeof(a)/sizeof(sizea) where a is a 2D array of type int and sizea is an int.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with 2d arrays
    By thamiz in forum C Programming
    Replies: 25
    Last Post: 05-25-2008, 05:06 AM
  2. 2D Array's, assigning chars.
    By gman89 in forum C Programming
    Replies: 9
    Last Post: 04-26-2008, 11:03 PM
  3. Initialising 2D and 3D arrays
    By fry in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 04:34 AM
  4. Reading 2d arrays from file?
    By Ringhawk in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2002, 09:05 PM
  5. how can i pass 2d arrays
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 11-02-2001, 07:33 AM