Search code examples
stringreversestring-concatenationpawn

Reverse string in PAWN language


I try to reverse word but stack in some problem which I can’t explain and don’t know what to do.

new word{8};
GetWord(coords, word);
printf ("%s\n", word);
new doubleWord {16};
new reversedWord {16};
strcat (doubleWord, word, 16);
printf ("doubleword = %s\n", doubleWord);
strcat (doubleWord, word, 16);
printf ("doubleword = %s\n", doubleWord);
ReverseWord(doubleWord, reversedWord);
strcat (reversedWord, reversedWord, 16);
printf ("doubleword = %s, length = %d\n", doubleWord, strlen(doubleWord));
printf ("doubleword = %s, reverseword = %s\n", doubleWord, reversedWord);

My reverse function:

ReverseWord(word{}, rev{}) {
    for (new i = 0; i < 8; i++){
        rev{i} = word{8-i};
    }
}

In function I reverse only one part because doubleWord is just cope of word and doesn’t matter which part to reverse. Then I concatenate it and after that value of doubleWord just vanish. I don’t know how to explaine this and don’t find explanation in PAWN guide. Here screenshot with results. first_reverse_test

I try to reverse whole word of course. Like this:

ReverseWord(word{}, rev{}) {
    for (new i = 0; i < 16; i++){
        rev{i} = word{15-i};
    }
}

And delete strcat:

printf ("doubleword = %s\n", doubleWord);
ReverseWord(doubleWord, reversedWord);
printf ("doubleword = %s, length = %d\n", doubleWord, strlen(doubleWord));

But then I come to reversedWord get doubleWord value in the end of it. Here screenshot with results. second_reverse_test

In second version I also try strdel to delete doubleWord value from the end:

printf ("doubleword = %s\n", doubleWord);
ReverseWord(doubleWord, reversedWord);
strdel(reversedWord,16,32);
printf ("doubleword = %s, length = %d\n", doubleWord, strlen(doubleWord));

but I get doubleWord modified again!. Here screenshot with results. third_reverse_test

Who can explane what happen? Does PAWN remember value of variable in heap or stack and get the last used variable? And how can I reverse word cause of this?


Solution

  • There are two issues with your code. First, you reserve 8 characters for the initial string, but the null terminating character is missing. If you want the strings to have 8 or 16 characters, the sizes should be 9 and 17.

    The second issue is that you are passing the length of the array in characters to strcat, but the function expects the size in cells. Combined with the fact the the strings do not fit in their target arrays, the function writes the null byte to a wrong place. This is the next array on the stack, leading to both doubleWord and word being "erased" (the first cell set to 0).

    Simply remove 16 from the arguments, since it should be filled automatically anyway. It it doesn't, use sizeof(doubleWord).