partida partida - 18 days ago 9
C++ Question

What's the difference between char str[] and char* str?

I have this code and it has problem.

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


but if I change
char* str
to
char str[]
.
it works fine.Why?

Answer

When you declare char str[] you are declaring an array of chars (which is accessible to be both read and written), and this array is initialized to some sequence of characters i.e. "This is test string" is copied to the elements in this array.

When you declare char* str, you are declaring a pointer that points directly to some constant literal - not a copy. These can only be read.

Comments