# of Elements in Array

This is a discussion on # of Elements in Array within the C++ Programming forums, part of the General Programming Boards category; Code: int array[] = { 1, 2, 3, 4, 5 }; int* ptr = array; int size1 = sizeof( array ...

  1. #1
    Unregistered
    Guest

    # of Elements in Array

    Code:
    int array[] = { 1, 2, 3, 4, 5 };
    int* ptr = array;
    int size1 = sizeof( array ) / sizeof( int);
    int size2 = sizeof( ptr ) / sizeof(int);
    size2 != size1.

    I know why they are different from technical point of view, but why should they behave differently ?

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    sizeof(array); returns the size of the array, which means sizeof(int) * NrOfElements (basically 4*5=20)
    sizeof(ptr); returns the size of a pointer, not what it's pointing to (basically 4)
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Adding More Array Elements?
    By Vermillion in forum C++ Programming
    Replies: 2
    Last Post: 09-14-2008, 11:02 PM
  2. coping elements not in array
    By lord in forum C++ Programming
    Replies: 2
    Last Post: 08-04-2008, 08:53 PM
  3. way to check 3 elements of array and set 4th
    By Syneris in forum C++ Programming
    Replies: 3
    Last Post: 01-09-2006, 11:30 AM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 05:15 AM
  5. A simple question about selecting elements in an array
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 11:37 PM

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