今天编写了一个很小很小的程序,有关数组和指针的,但是运行的时候电脑却发出了报警,仔细检查程序发现有个地方写错了,但也因为这个再一次体现了使用指针需谨慎小心的原则,一不留神就出错了。。。
#include<iostream>
char msg[]="Now is the time/n";
int main()
{
char *cp;
int i;
//Pointer access,pointer notation
for (cp=msg; cp; cp++) //错误就在这里,应该是 *cp,循环判断时若是cp,它所存储的内存地址一直不为空,那么这个
循环将是无限循环,必然会报错
std::cout << *cp;
//subscript access,subscript notation
for (i=0; msg[i]; i++)
std::cout << msg[i];
//Pointer access,subscript notation
for (cp=msg; cp[0]; cp++)
std::cout << cp[0];
//subscript access,pointer notation
for (i=0; *(msg+i); i++)
std::cout << *(msg+i);
//pointer and subsript access,pointer notation
for (i=0,cp=msg; *(cp+i); i++)
std::cout << *(cp+i);
//pointer and subscript access,subscript notation
for (i=0,cp=msg; cp[i]; i++)
std::cout << cp[i];
return 0;
}