Char*的使用

//============================================================================
// Name        : test_char.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;

char * test1 ()
        {
            char t1[] ="abcdefg";
            return t1;
        }
char * test2()
        {
            char *t2 ="123456789";
            return t2;
        }
int test3()
{
    static int count=0;                   //静态局部变量
    count++;
    return count;
}

int main() {
    char a[] = "hello";
    char *p = a;                          //指针
    int length = strlen(a)+1;
    char *q = new char [length];         //划内存
    char &t=a[0];                        //引用

    strcpy(q, a);
    cout << sizeof(a) << a << endl;
    cout << sizeof(p) << q << endl;
    cout << sizeof(q) << q << endl;
    cout << sizeof(t) << t << endl;

    cout << a+1 <<endl;              //不能用a++
    cout << ++p <<endl;
    cout << ++q <<endl;
    cout << ++t <<endl;

    char b[] ="hello";
    char *c = "world";                   //vs上面等于 const char *c = "world"
    b[0] = '0';
//    c[0] = '0';                         //在vs上面无法修改,在eclipse上面修改成功
    cout << b <<"\t" <<c << endl;      


    char *d = NULL;                     //字符指针初始化为NULL
    d = test1();
    cout <<"d="<< d <<endl;             //栈空间释放,内存指针指向未知, 野指针

    char *e = NULL;
    e = test2();
    cout << "e="  << e <<endl;          //返回正确
//    e[0]='a';                           //在vs上面无法修改,在eclipse上面修改成功
    cout << "e2=" << e <<endl;

    for(int i=0; i<10; i++)
        test3();
    cout << test3();                   //输出为11,说明局部静态变量不会重新定义

}

转载于:https://www.cnblogs.com/charlexu/archive/2013/01/10/2854259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值