数组和指针的一个问题.
# include < iostream.h >
void main ()
{
char *week1[7] = { "sunday", "monday" , "thursday" , "wednesday" , "tuesday" , "friday" };
char week2[7][10] = { "sunday", "monday" , "thursday" , "wednesday" , "tuesday" , "friday" };
cout <<"week1:"<<endl;
cout<<week1[0]<<endl;
cout <<(*week1[0]);
for ( int i = 0; i < 7;i++ )
{
cout <<&week1[i] << " " << (void *)week1[i] << " " << *week1[i] <<endl;
}
cout << endl;
cout <<"week2:"<<endl;
cout<<week2[0]<<endl;
for ( i = 0; i < 7;i++ )
{
cout <<&week2[i] << " " << (void *)week2[i] <<endl;
}
cout << endl;
}
程序有时有问题,有时没有问题,有问题时,"week2:"和后面部分7输不出,请大家帮着看看啊,用什么手段才能确认问题出在哪呢?
[解决办法]
#include <iostream.h> void main () { char *week1[7] = { "sunday ", "monday " , "thursday " , "wednesday " , "tuesday " , "friday ", "saturday" }; // 你少了这个 char week2[7][10] = { "sunday", "monday" , "thursday" , "wednesday" , "tuesday" , "friday", "saturday"}; // 你还少了这个 cout << "week1: " <<endl; cout <<week1[0] <<endl; cout <<(*week1[0]); for ( int i = 0; i < 7;i++ ) { cout<<&week1[i]<< " " << (void *)week1[i] << " " << *week1[i] <<endl; } cout << endl; cout << "week2: " <<endl; cout <<week2[0] <<endl; for ( i = 0; i < 7;i++ ) { cout <<&week2[i] << " " << (void *)week2[i] <<endl; } cout << endl; }
[解决办法]
#include <iostream.h> #include <windows.h> int main( void) { char *week1[6] = {"sunday", "monday", "thursday", "wednesday", "tuesday", "friday"}; //只需要6个指针,为何定义7个,多定义了一个野指针,去掉!! char week2[6][10]="sunday", "monday", "thursday", "wednesday", "tuesday", "friday"}; cout <<"week1: "<<endl; cout <<week1[0] <<endl; cout <<*week1[0]; // for (int i=0; i<7; i++) 只有6个数组,为何循环7次 for (int i=0; i<6; i++) { cout <<&week1[i]<< " "<<(void *)week1[i]<< " "<< *week1[i] <<endl; } cout <<endl; cout << "week2: " <<endl; cout <<week2[0] <<endl; for ( i=0; i<6; i++ ) // 同上,应该是6 { cout <<&week2[i]<< " " << (void *)week2[i]<<endl; } cout << endl; return 0;}