Problem Passing a character array to a function

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 ??

void charModify(char*& charArray)
{
charArray[2] = 'r';
}

int main(int argc,char*argv[])
{
char* c = "karthick";
charModify(c);
}
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???

is value pointed by char* c read only???
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[])
{
    const char* str = "karthick";

    char* c = new char[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??
Last edited on
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.

so:

1
2
3
4
5
6

// const char* = const char*
const char* str1 = "const literal one";

// char* = const char*
char* str2 = "const literal two";


But the compiler is lenient and allows the promotion of a string literal const char* to a basic char* without much fuss.

But you should never attempt to write into one. In fact you should always do the proper thing and declare it const as in my first example above:

1
2
// const char* = const char*
const char* str1 = "const literal one";


That will prevent you accidentally writing into the string literal and causing an access violation of some kind. Or worse...

Thanks for promt replies Galik.

say if i declare


1
2
    // const char* = const char*
        char* str1 = "const literal one";


So if I use <const_cast> as

str1 = const_cast<char*> str1;


what ll happen?
Last edited on
Nothing.

But did you mean to say this?

1
2
3
const char* str1 = "const literal one";

str1 = const_cast<char*> str1;


It is okay to assign a char* to a const char*. But not the other way around.
Topic archived. No new replies allowed.