Gordon Burditt wrote:
How come this function doesn't work?
If you attempt to write on a quoted string literal, you invoke
the wrath of undefined behavior.
What *does* it do on your machine? Smegmentation fault?
void shift(char** list, int index) {
char buff = (*list)[0];
memmove((*list)+1, *list, index);
(*list)[0] = buff;
return;
}
I call it like so:
char* t = "abcde";
shift(&t, 1);
I expect t = "bacde"
or
shift(&t, 0) would not effect t at all.
Anyway, I made it work by creating another character array inside the function.
I then did a memcpy to copy list to this temp buffer and the memmove function
worked correctly when I passed in the temp buffer local to the function. I
would like to understand why the above code will not work. Am I doing something
wrong?
You are attempting to write on a string literal. That's bad.
Gordon L. Burditt
It generated a segmentation fault. I thought that I would need to pass in a
poniter to the string that I was modifying for the changes to effect to the
string outside the function.
I'm going to try the code that pete posted to see if it will work. I still
don't understand why my function wasn't working. Could you explain writing on a
string literal?
Assuming pete's code works with this function signature:
void shift(char* list, size_t index)
why would it fail with my signature? I'm just passing a pointer to the string.
void shift(char** list, size_t index)?
/* BEGIN pete's code */
#include <stdio.h>
#include <string.h>
void shift(char* list, size_t index);
int main (void)
{
char t[] = "abcde";
shift(t, 1);
puts(t);
return 0;
}
void shift(char* list, size_t index)
{
char buf = list[1];
memmove(list + 1, list, index);
list[0] = buf;
}
/* END pete's code /*