字符數組和int數組的不同

#include<iostream>
using namespace std;
void main()
{
	char a[]="hello";
	char b[]="hello";
	cout<<a<<'\n'<<*b<<endl;
}

猜猜打印輸出什麼?

hello

h

 

#include<iostream>
using namespace std;
void main()
{
	int a[]={4,5,6};
	int b[]={4,5,6};
	cout<<a<<'\n'<<*b<<endl;
}

猜猜打印輸出什麼?

0018FF38

4

 

這說明int數組和字符數組在輸出機制上是不同的。

另外,字符數組"hello"在電腦中會自動變成"hello\0"

所以

char s[5]="hello"; 會報錯

但是

char s[5]={'h','e','l','l','o'};不會報錯,但是輸出會有問題

#include<iostream>
using namespace std;
void main()
{
    char a[5]={'h','e','l','l','o'};
    char b[5]={'h','e','l','l','o'};
    cout<<a<<'\n'<<*b<<endl;
}

上面的輸出大概是系統去尋找'\0',把找到之前的經過的數據都輸出造成的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章