Kunal
Kunal

Reputation: 511

Simple String Manipulation

Suppose we have char *a ="Mission Impossible";

If we give cout<<*(a+1), then the output is i.

Is there any way to change this value, or this is not possible?

Upvotes: 0

Views: 145

Answers (4)

asveikau
asveikau

Reputation: 40264

char a[] = "Mission Impossible";

a[1] = 'x';

String literals cannot be modified. Typically they are placed a section of the binary that will be mapped read-only, therefore writing to them generates a fault. (This is implementation-defined behavior, but this happens to be the most common implementation these days.)

By declaring the string as a character array it is writable. The other alternative would be to duplicate the string literal into heap memory, either through malloc, new, or std::string.

Upvotes: 2

Naveen
Naveen

Reputation: 73493

No, the char* a is actually read-only and if you try to modify the content you will get undefined behavior. You should ideally declare a as const char*.

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75150

Yes, there are several ways to do this, but you have to make a copy of the string first because if you didn't, you'd be modifying memory you're not allowed to (where string literals are stored).

const char* a = "Mission Impossible"; // const char*, not char*, because we can't
                                      // modify its contents
char buf[80] = {}; // create an array of chars 80 large, all initialised to 0
strncpy(buf, a, 79); // copy up to 79 characters from a to buf

cout << *(buf + 1); // prints i

buf[1] = 'b';

cout << *(buf + 1); // prints b

*(buf + 1) = 't';

cout << buf[1]; // prints t

That said, if this exercise is not for learning purposes, it is highly recommended that you learn and use std::string rather than C-style strings. They are superior in almost every way and will result in far less frustration and errors in your code.

Upvotes: 2

Theocharis K.
Theocharis K.

Reputation: 1341

The simplest way to change that is doing *(a+1)='value_you_want';

This will change the content of a pointer (your case pointer is a+1) to the value you set.

Upvotes: 0

Related Questions