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/p/2854259.html