user12945091
user12945091

Reputation:

c++ change array by index inside function

void changeArray(char* str1) {
        str1[0] = 'f';
}

int main() {
        char* msg1 = "andrew";
        changeArray(msg1);
        cout << msg1 << endl;
        return 0;
}

Hi guys,i dont understand why i'm getting segmentation fault. pointers cannot be accessed by index inside functions? (C++)

Upvotes: 1

Views: 40

Answers (2)

songyuanyao
songyuanyao

Reputation: 172874

You're trying to modify string literal, which leads to undefined behavior.

Attempting to modify a string literal results in undefined behavior: they may be stored in read-only storage (such as .rodata) or combined with other string literals:

const char* pc = "Hello";
char* p = const_cast<char*>(pc);
p[0] = 'M'; // undefined behavior

And, char* msg1 = "andrew"; is not allowed since C++11,

In C, string literals are of type char[], and can be assigned directly to a (non-const) char*. C++03 allowed it as well (but deprecated it, as literals are const in C++). C++11 no longer allows such assignments without a cast.

You can construct and pass a char array instead.

String literals can be used to initialize character arrays. If an array is initialized like char str[] = "foo";, str will contain a copy of the string "foo".

E.g.

int main() {
    char msg1[] = "andrew";
    changeArray(msg1);
    cout << msg1 << endl;
    return 0;
}

Upvotes: 3

H-005
H-005

Reputation: 505

In int main() you declared msg1 as a pointer to a char, not as an array of chars. Do this: char msg1[] = "andrew";.

Upvotes: 0

Related Questions