Help Required - It is urgent

May 11, 2011 at 9:58am
Here is a piece of code snippet:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
char ** func()
{
char *a[3];
int i = 0;
for(i =0;i<3;i++)
{
a[i] = (char *)NULL;
}
a[0] = (char *) malloc(100);
strcpy(a[0],"Senthil");
a[1] = (char *) malloc(100);
strcpy(a[1], "Kumar");
printf("In func()\n");
char **p = a;
while(*p != NULL)
{
printf("%s \n",*p++);
}
return a;
}
int main(int argc, char *argv[])
{
char **a = func();
char **p = a;
while(*p != NULL)
{
printf("%s\n",*p++);
}
}
It displays :
In func()
Senthil
Kumar
Senthil
Kumar
    °╖µwΦ#σw
Uï∞âSVWUⁿï]♀ï≈@♦♠
Please lemme where Iam going wrong.
I am using Dev-C++ compiler.
Thanks in advance
MSS
Last edited on May 11, 2011 at 10:04am
May 11, 2011 at 10:04am
Use code tags: http://www.cplusplus.com/forum/articles/42672/
Give a better description to your problem(s): http://www.cplusplus.com/forum/articles/40071/
May 11, 2011 at 10:13am
your q is a mess..

one big problem i see, is when the function func() returns a -- which was localy defined (never a good idea).

try defining a as a global variable and check the results again..

if youll explain, what are you trying to do, and post a more readable q, i can try and help you more..
May 11, 2011 at 11:11am
The problem is that it works perfectly fine in func() function, but in main() the func() returns pointer to pointer to char, and it is accessing illegal memory location and prints the value of that memory location. Why the illegal memory location is accessed in main() function? Please help.
Thanks in advance
MSS
May 11, 2011 at 11:17am
closed account (D80DSL3A)
I think the problem is with the local array of 3 char pointers a[3]. That array is out of scope in main().
Try dynamically allocating it in func(), or make it global as suggested by btucho.
The pointer returned by func() points to this array.
Last edited on May 11, 2011 at 11:20am
May 12, 2011 at 1:39am
Thanks for the reply.If I have the global variable it can be accessed by all functions in the file, so I prefer to declare it as local variable.
One last question:
Is it of NO-USE having a function returning a char pointer, and when to declare one?
Thanks in advance
MSS
May 12, 2011 at 1:49am
You may prefer it to have it local, but it won't work. Make it global as suggested, or better yet, pass the array as parameter to the function, along with the size of the array. That way you are safe (and you can forget about returning anything from the function; it won't be necessary anymore).
Topic archived. No new replies allowed.