I am trying to get my basics rite. I tried to pass a reference to a char pointer to a function and modify the contents of the array but i get an access violation exception . can any one explain whats happening ??
int main(int argc,char*argv[])
{
char* c = "karthick";
*c='K'
charModify(c);
}
even this doesnt work,, does that mean that the character array is always a constant??
isnt there a way to make an in-place change of the characters???
The literal string in your code "karthich" is possibly being stored in read-only memory. So any attempt to write to those locations will trip an access violation.
Your compiler should at least warn you that you are assigning a constant to a non-const.
If you want to modify the value you need to ask for some memory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <cstring>
int main(int argc,char*argv[])
{
constchar* str = "karthick";
char* c = newchar[strlen(str) + 1]; // allocate enugh memory for the string and the end-of-string marker 0
strcpy(c, str); // copy your constant string into the new memory
*c='K' // overwrite it to your hearts content
charModify(c);
return 0;
}
Does that mean that, always char* some_Variable is interpreted as const char* some_variable.
So is it not possible to change the char* without allocating memory in heap??
Not quite. It means that and literal string like this; "my literal string" is interpreted as a const char* so assigning it to a char* (non-const) should give a compiler warning. Actually it should be an error but (I assume) due to a lot of loosely written C code its only a warning.