內存分配雖然成功,但是尚未初始化就引用它。 犯這種錯誤主要有兩個起因:一是沒有初始化的觀念;二是誤以為內存的缺省初值 全為零,導致引用初值錯誤(例如數組)。
內存的缺省初值究竟是什么並沒有統一的標准,盡管有些時候為零值,我們寧可信其無不可信其有。
所以無論用何種方式創建數組,都別忘了賦初值,即便是賦零值也不 可省略,不要嫌麻煩。
1 #include <iostream> 2 #include <string.h> 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 int main(int argc, char** argv) { 6 //聲明字符數組和字符型指針變量 7 char string[80],*p; 8 9 //拷貝字符串 10 strcpy( string, "I'll see you"); 11 cout<<"string:"<<string<<endl; 12 13 //追加字符串 14 p=strcat( string, " in the morning."); 15 cout<<"String: "<<string<<endl; 16 cout<<"p : "<<p<<endl; 17 return 0; 18 }