Srivatssan
09-27-2009, 12:01 AM
See the following function
#include
main()
{
char *fun();
printf("%s",fun());
}
char *fun()
{
char buffer[] ="Hello World";
return buffer;
}
When I call this function in main, I will get a garbage value.
My assumption is this:
Since I declare a function pointer, there will just be the default memory for the pointer. Since the char array is not a pointer, there will be separate memory for the array. Now the address of the func holds a value which is the address of the character. So when I use this type of function pointer, The printf tries to print the address of array which is stored as a value inside the address of the function. Thats why Im getting a garbage value.
But when I dont use function and do everything in main, then there is no problem. i.e
#include
{
char a[] = "Help me please!";
printf("%s", a);
}
For this , I will get the output.
So comparing these two, is my understanding on the concept is right? If not please explain. I am having my final test on this next week.
#include
main()
{
char *fun();
printf("%s",fun());
}
char *fun()
{
char buffer[] ="Hello World";
return buffer;
}
When I call this function in main, I will get a garbage value.
My assumption is this:
Since I declare a function pointer, there will just be the default memory for the pointer. Since the char array is not a pointer, there will be separate memory for the array. Now the address of the func holds a value which is the address of the character. So when I use this type of function pointer, The printf tries to print the address of array which is stored as a value inside the address of the function. Thats why Im getting a garbage value.
But when I dont use function and do everything in main, then there is no problem. i.e
#include
{
char a[] = "Help me please!";
printf("%s", a);
}
For this , I will get the output.
So comparing these two, is my understanding on the concept is right? If not please explain. I am having my final test on this next week.