Thread: Arrary Size

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    104

    Arrary Size

    I might just be too over accustom to vectors, but how do I get the size of an array in C++ again?

    I had to do this
    Code:
    int num[] = {0, 0, 0, 0};

    to fill up an arrary with only 4 zeros initially. Later on in the code I had to use a for loop to fill up the actual values, but can't remember how to get the size of the arrary so had to start from

    Code:
    for int i = 4 - 1; 


    Where 4 is the size of the array...

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    sz = sizeof(num)/sizeof(num[0]);

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Just remember that that will only work when you do it in the same scope as you created the array in. For example this wont work as wanted:
    Code:
    #include <iostream>
    using namespace std;
    
    void func(int ar[])
    {
    	cout << sizeof(ar)/sizeof(*ar) << endl;
    }
    
    
    int main() 
    {
    	int array[5];
    	cout << sizeof(array)/sizeof(*array) << endl;
    	func(array);
    }
    Will produce this output:
    5
    1
    STL Util a small headers-only library with various utility functions. Mainly for fun but feedback is welcome.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of array
    By goran00 in forum C Programming
    Replies: 38
    Last Post: 04-02-2008, 09:57 AM
  2. Heapsort
    By xENGINEERx in forum C Programming
    Replies: 2
    Last Post: 03-30-2008, 07:17 PM
  3. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  4. An exercise in optimization
    By Prelude in forum Contests Board
    Replies: 10
    Last Post: 04-29-2005, 03:06 PM