Arrary Size

This is a discussion on Arrary Size within the C++ Programming forums, part of the General Programming Boards category; I might just be too over accustom to vectors, but how do I get the size of an array in ...

  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
    ZuK
    ZuK is offline
    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,199
    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

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, 10:27 AM
  4. An exercise in optimization
    By Prelude in forum Contests Board
    Replies: 10
    Last Post: 04-29-2005, 03:06 PM

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