[LCP]passing struct to function

paul at pabryan.mine.nu paul at pabryan.mine.nu
Sun Nov 21 09:52:01 UTC 2004


On Sat, Nov 20, 2004 at 05:36:03PM -0600, Carlos Pruitt, Jr. wrote:
> I am trying to find what I am doing wrong.  This program compiles with 
> the warning message:

<snip>

Two problems. The one causing the error is:

print_mailing_list(&list_ptr);

It should be

print_mailing_list(list_ptr);

i.e. you're passing the address of the pointer itself and not the
address to which the pointer "points".

The second problem (which you'll see once you've fixed the first
problem) is that you haven't initialised your pointer. It's got
whatever junk happened to be in memory at the time. i.e. it doesn't
point at anything. 

You should really get in the habit of declaring pointers like:

struct mailing *list_ptr = NULL;

It can save trouble when debugging.

See below for the "fixed" code.

> 
> When I run the program, the output is:
> 
> f at carlos
> 
> 
> #include <stdio.h>
> #include <string.h>
> 
> struct mailing
> {
>        char first_name[60];
> };
> 
> void print_mailing_list(struct mailing *mlist)
> {
>        printf("%s\n", mlist->first_name);
> }
> 
> int main()
> {
>        struct mailing list =
>                {
>                        "carlos"
>                };
> 
> 
        struct mailing *list_ptr = NULL;

	list_ptr = &list;

>        if (strcmp(list.first_name, "carlos") == 0)
                print_mailing_list(list_ptr);
> 
>        return 0;
> 
> }
> 

Cheers,
Paul.




More information about the linuxCprogramming mailing list