Violetta Blejder
Violetta Blejder

Reputation: 1

Shifting a char array by N spots

I am trying to shift a character array by a number of specified spots.

For example, if n = 2, I would like my array "Hello." to become "llo." I've tried the following:

memmove(array, array+2, sizeof array - sizeof *array);

But it does not work. If:

char *array = "Hello."

I would like array to be "llo."

Any help would be appreciated. I've no clue how to do something this simple.

Upvotes: 0

Views: 75

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

In the case of

char *array = "Hello.";

Then the variable array isn't actually an array. It's a pointer to the first element of a constant array containing the literal string.

As literal strings are constant, they can not be modified, and any attempt to do it anyway leads to undefined behavior. And in fact your compiler should have warned you about it (listen to your compiler, and treat all messages (even warnings) as errors that must be fixed).

The correct definition would be

const char *pointer = "Hello.";

To solve your problem use an actual array:

char array[] = "Hello.";

Or better yet use std::string and its facilities. Like the ability to easily create sub-strings.

There's also the problem with sizeof when using pointers. The size of a pointer is the size of the pointer itself, not what it might point to. To reliable get the length of a C-style null-terminated string one must use strlen. And the size of an array is the size of the whole array, including possible null-terminator and other possibly uninitialized elements, while strlen only gets the number of characters in the string up to (but not including) the null-terminator.

Also note that the size of a single char is defined to always be 1, no matter its actual bit-with. Which means sizeof *array will always be 1, so you might as well save some effort and write the number instead.


The above answer is from a C++ perspective. The semantics of literal strings and pointers to them is very different in C!

In C literal strings aren't actually constant. However it's not allowed to modify them, making them in essence read-only. Attempting to modify a string literal in C still leads to undefined behavior, but the reason is a different one.

Upvotes: 1

Related Questions