-1

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?

partida
  • 501
  • 4
  • 20

2 Answers2

0

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.

Nasim Bahar
  • 115
  • 3
  • 13
-1

Because when you use char str[], str is allocated, but when you use char *str it is not.

user3794667384
  • 437
  • 7
  • 23