What is the difference between char s[] and char *s?
I have given an example of two codes based on the given link. Assuming getstring() a function.
char *str = "GfG"; /* "GfG" is stored in read only part of shared segment */
/* str has auto storage duration,so stored on the stack
/* No problem: remains at address str after getString() returns*/
return str;
AND
char str[] = "GfG"; /* "GfG" is stored in read only part of shared segment */
/* str has auto storage duration,so stored on the stack.
/* Problem: string may not be present after getSting() returns */
return str;
As both have automatic storage duration and both variables stored on the stack segment.
Then, why return str works for the first one and not for the second one ?
getString()is left. However in the second,"GfG"is not really a string literal and does not have a static lifetime, it's lifetime is bound to the scope in which it was allocated. In this way, the pointer returned by the second would be invalid and attempting to read it will invoke undefined behaviour.str[]asstatic char, it won't be destroyed when you exit the function.