码迷,mamicode.com
首页 > 编程语言 > 详细

数组类型与sizeof

时间:2016-01-16 01:34:30      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

以char类型为例:

char a[100];     //a类型为char[100]    &a类型为 char (*)[100]    *a类型为char

char *p = a;    //p类型为 char*, *p类型为char。 类型char[100]可隐式到char*转化,为此:

#include <iostream>

void test(char *p) //即使形参为char p[]或char p[100]
{
    //p类型为char *,一指针类型。即使传递的实参类型是char[100],也会退化到char*
    std::cout << sizeof(p) << std::endl; //编译时计算,指针大小为4
    
    p[0] = z;
}

int main()
{
    char a[100] = "abcdef";
    test(a);

    std::cout << a << endl;//"zbcdef"  
    return 0;  
}

形参可以改为char (*p)[100]或 char (&p)[100] ,必须要指定大小为100,因为char[100]不能转为char (&)[],char (*)[100]也不能转为char (*)[] ,你可能想定义a时改为char a[] = "abcdef";呢~~~不行a大小编译时计算,它的类型为char[7]而不是char[]

技术分享
#include <iostream>

void test(char (*p)[100])
{
    std::cout << sizeof(*p) << std::endl; //形参已经显示指定大小了,可以肯定输出100了。

    (*p)[0] = z;
}

int main()
{
    char a[100] = "abcdef";
    test(&a);

    std::cout << a << std::endl;//"zbcdef"
    return 0;  
}
使用char (*p)[100]
技术分享
#include <iostream>

void test(char (&p)[100])
{
    std::cout << sizeof(p) << std::endl; //形参已经显示指定大小了,可以肯定输出100了。

    p[0] = z;
}

int main()
{
    char a[100] = "abcdef";
    test(a);

    std::cout << a << std::endl;//"zbcdef"
    return 0;  
}
使用char (&p)[100]

传递指针变量时,有时可能需要传递的是指针的指针或指针的引用
有时,如果直接传递指针,如:

#include <iostream>

void AllocMem(char *p, int size)
{
    if(p != NULL)
        delete []p;

    p = new char[size];
}

int main()
{
    char *pstr = NULL;
    AllocMem(pstr, 100);
    
    //然而pstr依旧为NULL,执行下面的语句将运行出错
    //strcpy(pstr, "hello world");
    //...

    delete []pstr;
    return 0;  
}

若传递指针的引用:

#include <iostream>

void AllocMem(char *&p, int size)
{
    if(p != NULL)
        delete []p;

    p = new char[size];
}

int main()
{
    char *pstr = NULL;
    AllocMem(pstr, 100);
    
    strcpy(pstr, "hello world");
    std::cout << pstr << std::endl;//正常输出 hello world

    delete []pstr;
    return 0;  
}
技术分享
#include <iostream>

void AllocMem(char **p, int size)
{
    if(*p != NULL)
        delete [](*p);

    *p = new char[size];
}

int main()
{
    char *pstr = NULL;
    AllocMem(&pstr, 100);
    
    strcpy(pstr, "hello world");
    std::cout << pstr << std::endl;//"hello world"

    delete []pstr;
    return 0;  
}
指针的指针

 

数组类型与sizeof

标签:

原文地址:http://www.cnblogs.com/sfqh/p/5134834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!