We know that the
sizeof(variable) returns the size of the variable and sizeof(pointer) returns
the amount of memory that can be addressed in bytes.
Try this program:
Output you get will be:
int p[4];
we know that p points to the first element in the array so the sizeof(p) should return the size of the memory being addressed, and so p is same as &p[0] and so sizeof(p) and sizeof(&p[0]) should be same.But that is not the case, sizeof(p) gives the sizeof the array in bytes i.e sizeof(int)*4 in this case.
Try this program:
01
|
#include
|
02
|
#include
|
03
|
using namespace std;
| |
04
|
void sz(int p[]){
|
05
|
cout<<"sz:
"<<sizeof(p)<<"\n";
| |
06
|
}
|
07
|
int main(){
| |
08
|
int p[]={1,2,3,4};
|
09
|
cout<<"main:
"<<sizeof(p)<<"\n";
| |
10
|
sz(p);
|
11
|
cout<<"main:
"<<sizeof(p)<<"\n";
| |
12
|
cout<<"sizeof(p):"<<sizeof(p)<<"
sizeof(&p[0]):"<<sizeof(&p[0])<<"\n";
|
13
|
return 0;
| |
14
|
}
|
Output you get will be:
1
|
main: 16
|
|
2
|
sz: 8
|
3
|
main: 16
| |
4
|
sizeof(p):16 sizeof(&p[0]):8
|
int p[4];
we know that p points to the first element in the array so the sizeof(p) should return the size of the memory being addressed, and so p is same as &p[0] and so sizeof(p) and sizeof(&p[0]) should be same.But that is not the case, sizeof(p) gives the sizeof the array in bytes i.e sizeof(int)*4 in this case.
No comments:
Post a Comment