Possible Duplicate:
Modifying a C string: access violation
int main()
{
char str_1[7] = "string";
char* str_2 = new char[7];
str_2 = "string";
str_1[2] = 'a'; //ok
str_2[2] = 'a'; //error
return 0;
}
i get “access violation” error here str_2[2] = 'a';
I don’t understand why i can’t access dynamic string via index here? (VS2010) Thanks.
You can not assign to a string like you do. Instead of copying the strings contents you copy the pointer. Thus
str_2now points to a string literal and can not be modified. To copy string’s contents usestrcpy.Even worse- in your version of the code there is a memory leak for the memory allocated for
str_2in the line where you callnew.