• sizeof(数组名)和sizeof(指针)


    在做这道题时:

    32位环境下,int *p=new int[10];请问sizeof(p)的值为()
    A、4              B、10              C、40               D、8

    我以为正确答案为C,int类型为32位,占四个字节,10个自然就是40了,结果正确答案为A,只是指针p占的空间。

    因此写段代码测试一下:

     1 #include<iostream>
     2 using namespace std;
     3 void fun(int P[])//P这里作为指针使用
     4 {
     5 cout<<"在函数中"<<sizeof(P)<<endl;
     6 }
     7 int main()
     8 {
     9 int A[10];
    10 int* B=new int[10];
    11 cout<<"数组名"<<sizeof(A)<<endl;
    12 cout<<"指针"<<sizeof(B)<<endl;
    13 fun(A);
    14 }

    或者

     1 #include<iostream>
     2 using namespace std;
     3 void fun(int *P)
     4 {
     5     cout<<"在函数中"<<sizeof(P)<<endl;
     6 }
     7 int main()
     8 {
     9     int A[10];
    10     int* B=new int[10];
    11     cout<<"数组名"<<sizeof(A)<<endl;
    12     cout<<"指针"<<sizeof(B)<<endl;
    13     fun(A);
    14 }

    结果输出: 

    数组名40
    指针4
    在函数中4

    由此可见,数组名并不是完全等同于指针。虽然它们都可以通过指针方式访问数组。

    但是数组在作为函数参数传递过程中,会退化成指针。这也是为什么指针作为参数传递时,经常要一个长度。(wsj注:指针作为形参时,通常再加上一个形参——这个指针的长度)

    转自:http://blog.csdn.net/kangroger/article/details/20653255

  • 相关阅读:
    HDU 5640 King's Cake
    HDU 5615 Jam's math problem
    HDU 5610 Baby Ming and Weight lifting
    WHU1604 Play Apple 简单博弈
    HDU 1551 Cable master 二分
    CodeForces659C Tanya and Toys map
    Codeforces 960E 树dp
    gym 101485E 二分匹配
    Codeforces 961E 树状数组,思维
    Codeforces Round #473 (Div. 2) D 数学,贪心 F 线性基,模板
  • 原文地址:https://www.cnblogs.com/liushui-sky/p/5584004.html
Copyright © 2020-2023  润新知