sizeof (array name) and sizeof (pointer)

When doing this question:

In a 32-bit environment, int * p = new int [10]; May the value of sizeof (p) be ()
A, 4 B, 10 C, 40 D, 8

I thought the correct answer was C, the int type was 32 bits, and it took four bytes. Ten of them would naturally be 40. The correct answer is A, which is just the space occupied by the pointer p.

So write a piece of code to test:

#include<iostream>
using namespace std;
void fun(int P[])//P这里作为指针使用
{
cout<<"在函数中"<<sizeof(P)<<endl;
}
int main()
{
int A[10];
int* B=new int[10];
cout<<"数组名"<<sizeof(A)<<endl;
cout<<"指针"<<sizeof(B)<<endl;
fun(A);
}

or

#include<iostream>
using namespace std;
void fun(int *P)
{
    cout<<"在函数中"<<sizeof(P)<<endl;
}
int main()
{
    int A[10];
    int* B=new int[10];
    cout<<"数组名"<<sizeof(A)<<endl;
    cout<<"指针"<<sizeof(B)<<endl;
    fun(A);
}

Results output: 

Array name 40
pointer 4
in function 4

 

It can be seen that the array name is not completely equivalent to the pointer. Although they can all access arrays by pointer.

However, when the array is passed as a function parameter, it will degenerate into a pointer. This is why pointers often pass a length when passed as a parameter. (Wsj note: when the pointer is used as a formal parameter, usually add a formal parameter-the length of this pointer)

From: http://blog.csdn.net/kangroger/article/details/20653255

Published 42 original articles · Like 10 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/qq_37659294/article/details/102328093