-1

so this is the code for reversing a string

#include<stdio.h>

char* function(char *);
int main()
{   
   char a[]="computer";
   printf("%s", function(a));
   return 0;
}

char* function(char *p)
{
   int l,i;
   char t;
   for (l=0;*(p+l)!='\0';l++);
   for(i=0; i<(l/2) ; i++)
    {
        t=*(p+i);
        *(p+i)=*(p+l-1-i);
        *(p+l-1-i)=t;
    }

   return (p);
}

but if i change printf("%s", function(a)); in the main body to

printf("%s", function("computer"));

there is no output (the output is blank) in dev c++.... but it gives the desired output in turbo c++ even with this change....why is that?

piku_baba
  • 59
  • 7
  • 2
    Your program invokes undefined behavior when you write to a string literal with the second version. There are at least a thousand duplicates of this issue on this site, but the title's rarely reflect the actual issue, and are so divergent they're surprisingly difficult to find. Turbo C++ is probably older than *you* are, so get a modern compiler and turn up your warnings to pedantic levels. – WhozCraig Nov 20 '18 at 20:57
  • 1
    *Exact* duplicate of [Reversing a string literal in C with pointers](https://stackoverflow.com/q/43350179/2564301) – Jongware Nov 20 '18 at 20:57
  • 1
    Tip: Don't use `l` and `1` and `i` in arithmetic expressions. – Tim Randall Nov 20 '18 at 20:58
  • 1
    @TimRandall because we can get it mixed up right? – piku_baba Nov 20 '18 at 21:01
  • @AnasAziz Yes, it's difficult to read. Personally I don't like to use single letter variable names, except in `for` loops or cases where the meaning is super-obvious. I like to use one or two word names where possible. – Tim Randall Nov 20 '18 at 21:05

1 Answers1

3

Parameter "computer", which you pass to function, is a string literal, and changing/manipulating the contents of a string literal is undefined behaviour. That's what you are experiencing - something undefined.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58