tags:

views:

180

answers:

1

C99

I am using a pointer to pointer and passing it into a function to display the names.

However, when I go through the debugger. The pointer to pointer in the parameter points to nothing. However, I am using it to display all the names in main.

If I was passing an integer the integer value would still be there. Why not a pointer to pointer?

Does this have something to do with scope or do I need to allocate memory using malloc or calloc for the pointer to pointer?

Many thanks for any suggestions,

#include <stdio.h>

void display_names(char **first_names);

int main(void)
{
    char *names[] = {"peter", "Mary", "John", 0};
    char **print_names = names;

    while(*print_names)
    {
     printf("Name: %s\n", *print_names);
     *print_names++;
    }

    display_names(print_names);

    getchar();

    return 0;
}

void display_names(char **first_names)
{
    while(*first_names)
    {
     printf("First name: %s\n", *first_names);
     first_names++;
    }
}
+6  A: 

In your while loop, you loop until print_names points to nothing, and then you pass it to display_names. At this point, *print_names == 0. Instead of that while loop, try:

char **print_names = names;
while(*print_names)
{
        printf("Name: %s\n", *print_names);
        *print_names++;
}
print_names = names;
display_names(print_names);

This should print out the names twice - once from the while loop and once from the function call.

Nathaniel Flath
Rather than declaring another temp pointer to pointer. Could this be a better way to assign the names again before the function call. print_names = names; display_names(print_names);
robUK
yeah, that owould work as well. I changed my answer to reflect this.
Nathaniel Flath
The function call could simply be: display_names(names);
Jonathan Leffler