• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 305
  • Last Modified:

Getting sizeof a dynamically allocated array?

    I've got something like this:

int x = 0;
char* Array = NULL;
cin >> x;
Array = new char[x];
cout << sizeof(Array);

Why is it that sizeof(Array) always outputs 4??  If I change the type of array to int, it still gives me 4.  Is there any way to use the sizeof function to act normally? Or maybe there's another function...?

Thanks in advanced,
  • 2
1 Solution
Array is a pointer, I guess you are using system with 32-bit pointers.

sizeof interprets argument as an array if it IS an array.
sizeof operator is done in compilation time. The only thing compiler knows about Array is that this is pointer char*, which has 32 bits size. To get size of dynamically allocated array write:

cout << sizeof(char)*n;
If you declare array by such way:

char Array[10];

siseof(Array) is 10 (compiler knows it in compilation time). sizeof any pointer is always equals to pointer size in operating system (32 for Win32).
UngeniousAuthor Commented:
okay duh, it's late at night sorry... since i was using char data-type I was used to each frame of an array = 1 therefore I thought sizeof gave the number of frames in the array.  and yeah I just read that part about dynamically allocated arrays to return the # of bytes to store one address.  So, I guess as Alex said, sizeof is done in compilation time & I can't get the sizeof to act "normally". & I have to just use the variable.  Thanks Alex. I need sleep.

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now