我有这个代码,它有问题。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* str
到char str[]
。 它工作正常。为什么?
我有这个代码,它有问题。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* str
到char str[]
。 它工作正常。为什么?
当你声明char str []时,你声明了一个字符数组(可以被读写),并且这个数组被初始化为一些字符序列,即“This is test string”被复制到这个数组中的元素。
当你声明char * str时,你声明了一个直接指向某个常量的指针 - 而不是一个副本。这些只能被读取。
因为当你使用char str []时,str被分配,但是当你使用char * str的时候不是。