Coli Coli - 3 months ago 26
C Question

C: twist char *

Note: I can't use any libs or includes!

I have the following Code:

void twstng(char * str, int end, int strt) {
if(strt != end && strt != end-1) {
int hlp = str[strt];

printf("strt %d end %d hlp %d\n", strt, end, hlp);

str[strt] = str[end-1];


str[end-1] = hlp;


twstng(str, strt+1, end-1);

and in the main function:

char * sol = "hello";
twisting(sol, 5, 0);

I want to twist the entire string. But the console shows:

strt 0 end 4 help 104

And then comes a memory access error. But why?

My second problem is, that in the original task the given string is a

const char * const str

How can I work with it in the twstng function?


Your char *sol is a pointer to the string "hello". Being a string literal, it is actually read-only, and thus when you pass the pointer to your function, you get an error when you modify the contents of the constant string "hello" through the pointer.

Regarding the second part of the question, const char * const (i.e., constant pointer to a constant char) would indeed be a better type for the pointer, as it would convey that the thing pointed to is constant. However, then you cannot pass this pointer to the function (because the function takes a pointer to a non-const char), and it is not clear from the information given how you are "allowed" to work around this. One way is to copy the string and modify the copy.

edit: And as pointed out by other answers, your recursive call mixes up the start and end arguments (by using the more logical order of start first).