I write a small program. My teacher tells me that this program not work since the return value from function foo() is not guaranteed to be preserved. I think this is correct usage of pointers. I dont think so. I think my teacher wrong. Please explain.
My teacher tells me that this program not work since the return value from function foo() is not guaranteed to be preserved. I think this is correct usage of pointers. I dont think so. I think my teacher wrong. Your teacher is(!) right. You're returning the address of an auto ("local") array from foo(). This array, like all auto objects, has automatic duration, which means that once you return from foo(), it goes out of existence, and any attempt to use it invokes undefined behaviour, which means it may do anything from appearing to work correctly to crash hard. Sure, it may _look_ like it still exists after the return, in this simple test program. However, you cannot rely on this at all. In any more realistic program you're likely to read garbage.
I write a small program. Code: #include <string.h> char *foo(void); char *a = "I like C"; int main(void) { if((strcmp(a,foo())) { printf("\n i like c"); You should in general terminate an output line with a newline in order to guarantee that it appears. } } char *foo(void) { char b[100] = "I like C"; return b; } My teacher tells me that this program not work since the return value from function foo() is not guaranteed to be preserved. I think this is correct usage of pointers. I dont think so. I think my teacher wrong. Your teacher is correct. The array b is not guaranteed to continue to exist after foo() returns. It might, for instance, be in a location that is not accessible after the function returns, or it might get overwritten. Make it static and it will work.