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?

Community
  • 1
  • 1
Jatin
  • 14,112
  • 16
  • 49
  • 78

3 Answers3

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

Andrew
  • 24,218
  • 13
  • 61
  • 90
  • Is something like this valid `int arr[n]` where n is entered by user? – Jatin Aug 01 '12 at 13:42
  • @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 – Andrew Aug 01 '12 at 13:43
  • surprisingly, It compiles on code::blocks – Jatin Aug 01 '12 at 13:45
  • @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. – R. Martinho Fernandes Aug 01 '12 at 13:47
  • @Jatin gcc has VLAs in C++ as an extension, I think Code::Blocks uses gcc. – Daniel Fischer Aug 01 '12 at 13:47
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.

yuri kilochek
  • 12,709
  • 2
  • 32
  • 59
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...