陣列的輸出:迴圈輸出字串的輸出:可以直接透過 cout<<字串名 輸出,因為在賦值時會自動在末尾加一個"\0",cout時檢測到 "\0" 輸出就會停止。但如果透過 char str2[]={"C","o","m","p","u","t","e","r"} 賦值不會在末尾加"\0",會繼續訪問其他記憶體,直到遇到 "\0" 停止輸出。sizeof() 輸出變數或常亮所佔的位元組數#include <iostream> using namespace std; int main () { int a[10]={1,2,3,4,5,6}; cout<<a<<endl; //輸出 a的地址0x7ffca791e2a0 for(int i = 0;i<10;i++) cout<<a[i]<<endl; //輸出 1 2 3 4 5 6 0 0 0 0,補0 char str[10]="Computer"; cout<<str<<endl; //輸出 Computer char str1[]="Computer"; cout<<str1<<"\t"<<"str1長度="<<sizeof(str1)<<endl; //輸出 Computer str1長度=9 char str2[]={"C","o","m","p","u","t","e","r"}; cout<<str2<<"\t"<<"str2長度="<<sizeof(str1)<<endl;//輸出 Computer]@ str2長度=8 return 0; }
陣列的輸出:迴圈輸出字串的輸出:可以直接透過 cout<<字串名 輸出,因為在賦值時會自動在末尾加一個"\0",cout時檢測到 "\0" 輸出就會停止。但如果透過 char str2[]={"C","o","m","p","u","t","e","r"} 賦值不會在末尾加"\0",會繼續訪問其他記憶體,直到遇到 "\0" 停止輸出。sizeof() 輸出變數或常亮所佔的位元組數#include <iostream> using namespace std; int main () { int a[10]={1,2,3,4,5,6}; cout<<a<<endl; //輸出 a的地址0x7ffca791e2a0 for(int i = 0;i<10;i++) cout<<a[i]<<endl; //輸出 1 2 3 4 5 6 0 0 0 0,補0 char str[10]="Computer"; cout<<str<<endl; //輸出 Computer char str1[]="Computer"; cout<<str1<<"\t"<<"str1長度="<<sizeof(str1)<<endl; //輸出 Computer str1長度=9 char str2[]={"C","o","m","p","u","t","e","r"}; cout<<str2<<"\t"<<"str2長度="<<sizeof(str1)<<endl;//輸出 Computer]@ str2長度=8 return 0; }