0

Here is the function:

void reverse(char* str)
{
    char * endOfString = str ; 
    char temp ; 
    if(str)
    { 
         while(*endOfString)
         {
         ++endOfString;
         }
         --endOfString ; 
         while(str < endOfString)
         {
         temp = *str ; 
         *str++ = *endOfString ; 
         *endOfString-- = temp ;
         }
    }

}

and with this input :

int main()
{
    char cStrg[3] = {'a','b','c'} ;
    reverse(cStrg) 
    return 0 ; 
}

The output looks like ths: � % %. If I enter a bigger input, lets just say :
char cStrg[6] = {'a','b','c','d','e','f'} ; the output looks like this : f e d c b a, which is perfectly fine, does anybody know what I am missing here ?

Sachamora
  • 479
  • 2
  • 13
Nikos
  • 387
  • 2
  • 15

2 Answers2

3

char cStrg[3] = {'a','b','c'}; is not a null terminated string, as expected by your reverse function. You should replace it by char cStrg[4] = {'a', 'b', 'c', 0}; or char* cStrg = "abc";

Andrei Bozantan
  • 3,781
  • 2
  • 30
  • 40
  • thanks a lot. any clue why that used to work with bigger inputs even though I never added the termination ? – Nikos May 31 '14 at 12:32
  • because of random luck with undefined behavior – quantdev May 31 '14 at 12:33
  • Your function may be working if for example you declare your array like `char cStrg[3] = {'a', 'b'}`, since the compiler will automatically initialize the missing elements with 0. Also the function may work sometimes due to the fact that the memory can contain a zero byte after the location of your array. – Andrei Bozantan May 31 '14 at 12:37
0

C strings - it's sequence of characters which ending by \0 character. All standard function in C working with that sort of string. So, if you want to work with string in C you must specify it.

Example:

`char str1[3] = {'a', 'b', 'c'};` // it's just array of characters and that's it
`char str2[3] = {'a', 'b', 'c','\0'};` // it's valid C-string 

If you forget to point '\0' at the end of array - you will not have "true" C-string. So if you try to work with str1 as with string you will retrieve UB.

char* str = "abc"; // that's like {'a', 'b', 'c', '\0'}; // '\0' character will be added automatically

alexzok
  • 81
  • 7