how to use sizeof(..)?

Started by
6 comments, last by wah_on_2 22 years, 2 months ago
int **num; int i; num = new *[10]; for(i=0;i<10;i++) num = new int; cout< = new int; num = i; } B.) int *num; int i; num = new [10]; for(i=0;i<10;i++) *(num + i) = i; Thank you. </i>
Advertisement
correct error:

sizeof(num); //on line 8

*num = i; //on line 20
sizeof return the size of the pointer, which is 4. To return 10, you need to keep track of how big the array is in your own variable, or look into the STL, and use std::vector
(then you would do cout<
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Thank you, i know how to use vector on MSDN now.

However, beside the vector, do i have another way to know the size of the **num?

why it can work?

int num[10]={0};
sizeof(num); //it display 40
None that you'd want to use, short of writing your own memory allocation routines.

Edit: I amend that. You can allocate one extra pointer, set it to NULL, then walk and count trough your int* array until you reach NULL. strlen() works similarly.

Edited by - Fruny on February 16, 2002 2:28:35 AM
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
For dynamic pointers, sizeof returns 4, always. For static pointers, it returns the total size of the array.
short Static [10];sizeof(Static) == 20short* Dynamic = new short [10];sizeof(Dynamic) == 4 


~CGameProgrammer( );

~CGameProgrammer( );Developer Image Exchange -- New Features: Upload screenshots of your games (size is unlimited) and upload the game itself (up to 10MB). Free. No registration needed.
quote:Original post by CGameProgrammer
For dynamic pointers, sizeof returns 4, always. For static pointers, it returns the total size of the array.
short Static [10];sizeof(Static) == 20short* Dynamic = new short [10];sizeof(Dynamic) == 4 


And

short* Foo = Static;
sizeof(Foo) == 4
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Oic, thank you your explaination about the different of sizeof static and dynamic. I clear now.

This topic is closed to new replies.

Advertisement