passing array of pointers to function 
Author Message
 passing array of pointers to function

Hi,

How do you pass an arbitrary array of pointers to a function such that
they can each be assigned to something so that the caller can observe
these assignments after the call? My code below is one of many attempts
to get a handle on how this is done however in this particular version I
get this error from gdb:

Program received signal SIGSEGV, Segmentation fault.
0x804841c in getlist (list=0xbffff8c0) at t10.c:13
13              *list[1] = n2;
(gdb)

Thanks as usual,

Michael B. Allen

/* t10.c */

#include <stdlib.h>
#include <stdio.h>

char *n1 = "fred";
char *n2 = "barney";

int
getlist(void ***list)
{
    *list[0] = n1;
    *list[1] = n2;
    return 2;

Quote:
}

int
main()
{
    int n = 2;
    char **names = malloc(sizeof *names * n);
    n = getlist((void ***)&names);
    printf("%s\n", names[0]);
    printf("%s\n", names[1]);
    return 0;

Quote:
}

Sent via Deja.com http://www.*-*-*.com/
Before you buy.


Sat, 25 Jan 2003 03:00:00 GMT  
 passing array of pointers to function

Quote:

> #include <stdlib.h>
> #include <stdio.h>

> char *n1 = "fred";
> char *n2 = "barney";

> int
> getlist(void ***list)

`void' here is bogus.  You should use `char'.

Quote:
> {
>     *list[0] = n1;

This is equivalent to *(list[0]), which is equivalent to **(list
+ 0).  Okay, but abstractionally challenged.

Quote:
>     *list[1] = n2;

This is equivalent to *(list[1]), which is equivalent to **(list
+ 1).  *BOOM*  

You mean (*list)[1], which is equivalent to *((*list) + 1).

Quote:
>     return 2;
> }

> int
> main()
> {
>     int n = 2;
>     char **names = malloc(sizeof *names * n);
>     n = getlist((void ***)&names);

Drop the cast.

Quote:
>     printf("%s\n", names[0]);
>     printf("%s\n", names[1]);
>     return 0;
> }

By the way, there's no need for the triple pointer here.  You
could do it just as well, and with less confusion, with a double
pointer.  You only need the triple pointer if you're going to
include something like
        *names = malloc (sizeof *names * n);
within getlist() itself.
--
"You call this a *C* question? What the hell are you smoking?" --Kaz


Sat, 25 Jan 2003 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. passing pointer to a function expecting an array

2. pass a pointer to array of structs to functions

3. Newbie question: Pointer to an array and passing it into a function

4. Passing 2-D pointer to array to function

5. Passing an array of pointers to functions

6. Simple, Pass Pointer of an Array to function

7. function pointers and function pointers array

8. Passing pointers to arrays of pointers....

9. Pointer to function passed to varargs function

10. Novice: Passing a function pointer to a function

11. How to use (pointer to function), and function and pointer to (pointer to function)

12. Prototyping a function passed a pointer to a function

 

 
Powered by phpBB® Forum Software