现在的位置: 首页 > 综合 > 正文

指针初始化引出的问题

2013年10月08日 ⁄ 综合 ⁄ 共 1283字 ⁄ 字号 评论关闭

小结如下:
(1)先看例子:
#include <iostream.h>

void main()
{
char *p,*p1="hello first!";
while((*(p++) = *(p1++)) != 0);

cout<<p<<endl;
}错处:p定义时没有初始化,p是指向不定,是一个野指针。
p++可能会引用非法的内存块。
编译时不会出错,但运行时会造成程序崩溃。

(2)把上面的p初始化为NULL
#include <iostream.h>

void main()
{
char *p=NULL,*p1="hello first!";
while((*(p++) = *(p1++)) != 0);

cout<<p<<endl;
}//也错,NULL表示没有任何指向。p++没有任何意义,运行时会造成程序崩溃。这里就应该想到不能对NULL的指针进行直接操作。

(3)现在为p初始化为" ":
void main()
{
char *p=" ",*p1="hello first!";

while((*(p++) = *(p1++)) != 0);

cout<<p<<endl;
}//错:p指向的是一个const常量的内容,可以通过*(p++)形式引用该值,但是不能改变它指向const的内容。
(4)#include <iostream.h>
#include <string.h>
void main()
{
 char c[]="";
 char *p=c,*p1="hello first!";
 char *p_start=p;
 while((*(p++) = *(p1++)) != 0);
 
 cout<<c<<endl;
}//此时数组是一系列的变量了,也就是p一有指向,二不是指向常量的而是指向变量的。所以按理应该行的。问题出在c太小,造成了数组越界,所以错掉!把c的大小改来不比"hello first!"小就行了。
(5)对于的就想到用new来初始化了:
#include <iostream.h>
#include <string.h>
void main()
{
 char *p,*p1="hello first!";
 p=new char;
 char *p_start=p;
 while((*(p++) = *(p1++)) != 0);
 
 cout<<p_start<<endl;
}//现在就可以了,哈,不过,我认为在new时最好还是把它的大小给指出来,
如new char[strlen(p1)+1];如果不指定大小,我想p++会指向一些已用得地址,而这些地址又不能随便改,就会造成诸如野指针样程序崩溃了。

小结:对于前面的问题,不防这样来写:
#include <iostream.h>
#include <string.h>
void main()
{
 char *p,*p1="hello first!";
 p=new char[strlen(p1)+1];
 //p=new char;//觉得最好别这样子,new char只相当于得到一个char对
 char *p_start=p;//象,分配一个字符的空间。
 while((*(p++) = *(p1++)) != 0);
 
 cout<<p_start<<endl;
}

抱歉!评论已关闭.