On Dec 14, 9:09 pm, CBFalconer <cbfalco...@yahoo.com> wrote:
> somenath wrote:
>
> > #include<stdio.h>
> > char *f1(void);
> > char *f1(void) {
> > char *abc ="Hello";
> > return abc;
> > }
>
> > int main(void ) {
> > char *p;
> > p = f1();
>
> > printf("%s\n", p);
> > return 0;
> > }
>
> > While compiling the above program as mentioned below I am getting
> > the meaning
> ... snip ...
> > jj.c:5: warning: initialization discards qualifiers from pointer
> > target type
>
> > I have two question
> > 1) What is the meaning of the warning ?
> > 2) is it safe to return the local pointer value (i.e return abc 
> > is correct ?
>
> > My understanding is we should not return address of local
> > variable .So above code may not be working always .
>
> Change "char *abc ="Hello";" to "const char *abc ="Hello";". You
> are not returning a pointer to local storage, you are returning the
> value of that local storage.
>
Just to clarify myself I would like to explain my understanding.
In the definition char *abc ="Hello";
Say 'H' is stored in address 100 and the 'e' will be stored in 108 and
so on . Now "abc" will have the value 100. When "return abc" is
getting executed it will try to return 100 . Is it not correct? If it
is so I am trying to return a address obtained locally. So it should
be wrong. I think I am missing the knowledge about string literal . Is
it handled specially than local variable .
Suppose
int x = 5;
return &x;
According to me we should not this, as address of x will be scrapped
after the execution flow returns from particular function.