Thread: Calculating # of Elements in Array

  1. #1
    Unregistered
    Guest

    Question Calculating # of Elements in Array

    There is something I don't really understand about calculating number of elements in Array.


    int array[] = { 10, 20, 30, 40 };

    int * ptr = array;

    int size1 = sizeof ( array ) / sizeof( int);
    int size2 = sizeof ( ptr ) / sizeof( int );

    Only size1 gives correct number of elements, not size2.

    How come size2 calculation does not work?
    Any thing I can do to make it work?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >int size2 = sizeof ( ptr ) / sizeof( int );
    This is a trick we all wish would work. What is happening is the sizeof operator is getting the size of ptr, not the size of what ptr points to. Since a pointer is usually the size of an int, the result of the division should be 1. And no, dereferencing ptr wouldn't work either.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. coping elements not in array
    By lord in forum C++ Programming
    Replies: 2
    Last Post: 08-04-2008, 07:53 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. calculating elements of arrays
    By Kristin in forum C Programming
    Replies: 2
    Last Post: 11-02-2003, 10:38 AM
  5. A simple question about selecting elements in an array
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 10:37 PM