2016-11-17 124 views
-1

我有這個代碼,它有問題。char str []和char * str有什麼區別?

#include <iostream> 
#include <stdio.h> 
using namespace std; 
void main() 
{ 
char* str="hello_world"; 
cout<<str<<endl; 
str[3]='\0'; 
cout<<str<<endl; 
} 

,但如果我改變char* strchar str[]。 它工作正常。爲什麼?

回答

0

當你聲明char str []時,你聲明瞭一個字符數組(可以被讀寫),並且這個數組被初始化爲一些字符序列,即「T​​his is test string」被複制到這個數組中的元素。

當你聲明char * str時,你聲明瞭一個直接指向某個常量的指針 - 而不是一個副本。這些只能被讀取。

-1

因爲當你使用char str []時,str被分配,但是當你使用char * str的時候不是。

相關問題