ant2009
ant2009

Reputation: 22486

Passing a pointer to pointer to character into a function

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++;
    }
}

Upvotes: 2

Views: 677

Answers (2)

new bie
new bie

Reputation: 3045

char *names[] = {"peter", "Mary", "John", 0};
char **print_names;

int main(void)
{        
    print_names = &names[0]; // point to peter
    while(*print_names)
        printf("Name: %s\n", *(print_names++));  // last address in here is John

    print_names = &names[0];  // reset point to peter before call display_names
    display_names(print_names+0);   // peter
    display_names(print_names+1);   // Mary
    display_names(print_names+2);   // John

    getchar();
    return 0;
}

void display_names(char **names_selected)
{
     printf("Name: %s\n", *names_selected);    
}

Upvotes: 0

Nathaniel Flath
Nathaniel Flath

Reputation: 16005

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.

Upvotes: 6

Related Questions