I want to reverse a string using pointer arithmetic. I wrote a small program based on what I read in "A Book on C" and basic programs I wrote myself (which worked to my satisfaction). Here is what I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void rv(char* str)
{
int l = strlen(str);
char* copy = (char*) malloc((l + 1) * sizeof(char));
assert(copy != NULL);
int i;
for (i = 0 ; i < l ; i++) { // copy str to copy in reversed order
*(copy + i) = *(str + (l - 1 - i));
}
for (i = 0 ; i < l ; i++) { //
*(str + i) = *(copy + i);
}
free(copy);
printf("Current string is %s\n", str);
}
int main(void)
{
char* s1 = "abcde";
rv(s1);
return 0;
}
The program crashes. From my tests, the problematic part is:
for (i = 0 ; i < l ; i++) { //
*(str + i) = *(copy + i);
}
I read similar questions, and it seems that this little piece of code should do no harm. actually, even if I replace that part with:
*(str + i) = 'c';
The program still crashes. It seems I can't even change one simple character of the string. what is the problem?
char *s1 = "abcde";uses a fixed string, set as immutable?