3

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

I declared a dynamic array like this:

int *arr = new int[n]; //n is entered by user 

Then used this to find length of array:

int len = sizeof(arr)/sizeof(int); 

It gives len as 1 instead of n . Why is it so?

7
  • 10
    Just use vector, you will save your self a lot of time. Commented Aug 1, 2012 at 13:41
  • 2
    int *arr = new int[n]; is declaring a pointer. std::vector<int> arr; is declaring a dynamic array. Commented Aug 1, 2012 at 13:42
  • You don't have a dynamic array -- you only have a pointer to the first element of a dynamic array. Commented Aug 1, 2012 at 13:45
  • @KerrekSB Other than using vector as an alternative, is there a way to find length of dynamic array. Commented Aug 1, 2012 at 13:48
  • 1
    @Jatin No, there is no way. You have to store the length and pass it where necessary. Commented Aug 1, 2012 at 13:49

3 Answers 3

12

Because sizeof does not work for dynamic arrays. It gives you the size of pointer, since int *arr is a pointer

You should store the size of allocated array or better use std::vector

Sign up to request clarification or add additional context in comments.

5 Comments

Is something like this valid int arr[n] where n is entered by user?
@Jatin: n must be const or const-expression. Otherwise it will not compile since the compiler does not know how much memory to allocate at compile time
surprisingly, It compiles on code::blocks
@Jatin Set your compiler to standards-compliant mode and turn all the warnings on (-std=c++98 or -std=c++0x or -std=c++11 and all of -Wall -Wextra -pedantic). It probably compiles because of a GNU extension.
@Jatin gcc has VLAs in C++ as an extension, I think Code::Blocks uses gcc.
11

Because arr is not an array, but a pointer, and you are running on an architecture where size of pointer is equal to the size of int.

Comments

0

Andrew is right. You have to save n somewhere (depends on where do you use it). Or if you are using .NET you could use Array or List...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.