Pointer trouble

K

Kelvin Moss

Hi all,

I am facing a problem with a library that allocates memory internally.
My basic problem is how to reflect changes in pointer values back in
main.

My library routine allocates dynamically and returns char ** (array of
strings). To track changes in main I pass a char*** and dereference the
passed value in foo (this is unsafe, don't know what it's pointing to).

void foo (char ***i, char ***j)
{
/* i and j are allocated dynamically here */
**i = lib_routine();
....
**j = lib_routine();

}
/* In main, i want to know changes made to pointer values */
int main(void)
{
char ***a, char ***b;
foo(a, b)
/* Do something with *a[0] and *b[0] */
}

But isn't it unsafe (I dereference an unknown pointer when I write **i
= lib_routine();) ? How do I track changes in pointer values in a
called function ?

Thanks

PS - I wanting something on the lines of a reference to pointer in C++.
 
K

Kelvin Moss

void foo (char ***i, char ***j)
{
/* i and j are allocated dynamically here */
**i = lib_routine(); Should be *i = lib_routine();
...
**j = lib_routine();
Should be *j = lib_routine();



}
 
L

Lawrence Kirby

Hi all,

I am facing a problem with a library that allocates memory internally.
My basic problem is how to reflect changes in pointer values back in
main.

My library routine allocates dynamically and returns char ** (array of
strings). To track changes in main I pass a char*** and dereference the
passed value in foo (this is unsafe, don't know what it's pointing to).

It is up to the caller to pass a pointer to something valid.
void foo (char ***i, char ***j)
{
/* i and j are allocated dynamically here */
**i = lib_routine();
...
**j = lib_routine();

That should be *i and *j
}
/* In main, i want to know changes made to pointer values */
int main(void)
{
char ***a, char ***b;
foo(a, b)

But your caller here isn't passing a valid pointer, it is passing
uninitialised values which is always an error. What you need is

char **a, char **b;
foo(&a, &b);

which is passing valid addresses if char ** objects that foo can write to.
/* Do something with *a[0] and *b[0] */

You now can.

Lawrence
 
K

Kelvin Moss

char **a, char **b;
foo(&a, &b);

which is passing valid addresses if char ** objects that foo can write
to.

oh yes..thanks much. I guess too many pointers and lack of sleep
confused me :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top