注册 登录
编程论坛 C++教室

大家帮忙看看啊,问题在那个注释里

zd123 发布于 2009-11-23 23:29, 546 次点击
// a.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<cstring>
using namespace std;
class Strclass
{
public:
    char *p;
    int length;
public:
    Strclass();
    Strclass(char *str,int len);
    char * getstring(){return p;}
    int getlength(){return length;}
};
Strclass::Strclass()
{
    p=new char[255];
    if(!p)
    {
        cout<<"Allocatinon  error!"<<endl;
        exit(1);
    }
    *p='\0';                                                     // 为什么是*p='\0' 难道p此时指到  最后面?????????  此时p不是指向内存块的头部吗
    length=255;
}
Strclass::Strclass(char* str,int len)
{
    if(strlen(str)>=len)
    {
        cout<<"Allocation too little memory!"<<endl;
        exit(1);
    }
    p=new char(len);
    if(!p)
    {
        cout<<"Allocation error!"<<endl;
        exit(1);
    }
    strcpy(p,str);
    length=len;
}

int _tmain(int argc, _TCHAR* argv[])
{
    Strclass ob1;
    Strclass ob2("This is a string .",100);
    cout<<ob1.p<<endl;
    cout<<ob1.getlength()<<endl;


    return 0;
}

2 回复
#2
flyingcloude2009-11-23 23:59
回复 楼主 zd123
p是指向头部,因为这个时候是一个空字符串,所以就存储了一个'\0'
#3
我心无疆2009-11-24 23:36
p=new char[255];只是开辟了一块内存,把内存的首地址给了p,但是内存中并没有存值。
1