• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 210
  • Last Modified:

Pointer allocation in function

Hi! I need some help with C pointers...

I try do something like that:

void func(char **f)
{

//      *f = (char **)malloc(3 * sizeof(char *));

        f = (char **)malloc(3 * sizeof(char *));
        f[0] = (char *)malloc(10 * sizeof(char));
        f[1] = (char *)malloc(10 * sizeof(char));
        f[2] = (char *)malloc(10 * sizeof(char));
        strcpy(f[0], "aaaaa");
        strcpy(f[1], "bbbbb");
        strcpy(f[2], "ccccc");
        printf("%s - %s - %s\n", f[0], f[1], f[2]);
        }
       
int main()
{
        char **f;

//      f = (char **)malloc(3 * sizeof(char *));

        func(f);
        printf("%s - %s - %s\n", f[0], f[1], f[2]);
        return 0;
        }

When I discomment one of two commented lines its work fine.

I know... this is a simple concept in pointers, but I'am desperate...

Thanks
0
ragys
Asked:
ragys
1 Solution
 
Jaime OlivaresSoftware ArchitectCommented:
This question is the same as:
http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_21213626.html

Another alternative is:

void func(char ***g)    /* triple asterisc needed */
{
        char **f;  

        f = (char **)malloc(3 * sizeof(char *));

        f[0] = (char *)malloc(10 * sizeof(char));
        f[1] = (char *)malloc(10 * sizeof(char));
        f[2] = (char *)malloc(10 * sizeof(char));
        strcpy(f[0], "aaaaa");
        strcpy(f[1], "bbbbb");
        strcpy(f[2], "ccccc");
        printf("%s - %s - %s\n", f[0], f[1], f[2]);
        *g = f;        
}
       
int main()
{
        char **f;

        func(&f);    /* notice the ampersand */
        printf("%s - %s - %s\n", f[0], f[1], f[2]);
        return 0;
}

0
 
dennis_georgeCommented:
Repeated Question !!!!!

Repeated Answer !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

:-)
Its the simple concept of "Pass by Value" which you are missing here...... whatever you pass to a function it will be passed as pass by value....

So.............

char **f  = NULL; // pointer to pointer

func(f) ; // Here you are passing the value of pointer to pointer i.e. NULL

And in your function you are allocating memory and assiging it to f .... And since it will be a local copy of the funciotn 'func' it won't be reflected in main().......

i.e. after function call 'f' will be NULL .... whatever you do in func.....

cheers
Dennis
0
 
ragysAuthor Commented:
Sorry Jaime, but in another question I accept the answer before I test the solution...

But, its a good solution too...


Thanks.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now