structs help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Cooke

    #1

    structs help

    Hi I am very new to C. I am trying to figure out how to initialize
    a struct in my main program.
    The struct is declared in anouther header file like this...
    typedef struct ln {
    int key;
    int data;
    struct ln *next;
    } listNode, *listNodePtr;

    just to test in my main method I tried to initialize the
    listNodePtr variable to null like this...

    listNodePtr *head = NULL;

    First as far as I understand listNode and *listNodePtr are
    variables of type ln. However I have also learned, so I thought,
    that listNodePtr is an alias to the struct ln. So my statement
    above should be legal. Is It?

    When I try to pass my new listNodePtr variable *head to my
    listInsert method like........

    listInsert(head ,1,2);

    it doesn't work. It builds but at run time my program hangs
    when inside the listInsert method the first if condition
    tries to determine of the listNodePtr *list is null or not.
    i.e. if( *list == NULL )..... this is where the program quits.

    The method definition looks like...

    void listInsert(list NodePtr *list, int key, int value)

    I am assuming the body of the method is correct as this code
    was given to us to use by my Prof.

    Please help what am I doing wrong during my initialization?
    How do I use structs defined like the one above?

    Thanks in advance.
  • Martin Ambuhl

    #2
    Re: structs help

    Dave Cooke wrote:[color=blue]
    > Hi I am very new to C. I am trying to figure out how to initialize
    > a struct in my main program.
    > The struct is declared in anouther header file like this...
    > typedef struct ln {
    > int key;
    > int data;
    > struct ln *next;
    > } listNode, *listNodePtr;
    >
    > just to test in my main method I tried to initialize the
    > listNodePtr variable to null like this...
    >
    > listNodePtr *head = NULL;[/color]

    If you avoid using typedefs for pointers to structs, you won't make this
    error.

    You mean either
    listNode *head = NULL; /* better */
    or
    listNodePtr head = NULL; /* not so good */

    Comment

    • Leor Zolman

      #3
      Re: structs help

      On Sat, 03 Apr 2004 22:36:05 -0600, Dave Cooke
      <dcooke@ee.uman itoba.ca> wrote:
      [color=blue]
      >Hi I am very new to C. I am trying to figure out how to initialize
      >a struct in my main program.
      >The struct is declared in anouther header file like this...
      >typedef struct ln {
      > int key;
      > int data;
      > struct ln *next;
      >} listNode, *listNodePtr;[/color]

      The statement above is mixing the "typedef" mechanism with the syntax
      of declaring and defining structures. The simplest usage of typedef
      is:

      typedef some-type identifier;

      which results in the identifier being another name for the type
      specified by some-type. If you want to define a struct /instance/
      named listNode and a pointer to it, you'd simply omit the word
      "typedef" above and that would be what you'd get (and you wouldn't
      have any typedefs, so to later define another struct of the same type
      you'd say:
      struct In anotherOne;
      ).

      If you want to create a typedef (type alias) for a struct of the type
      you're using, you'd do something like this:

      typedef struct In {
      /* all your member declarations */
      } In;

      I used the same name for the typedef as for the structure tag, because
      that happens to me my own personal style; you might choose to do
      otherwise, but this is perfectly legal.

      So after that, you could just say:

      In listNode, *listNodeptr;

      Because the compiler would have been confused from the point of your
      original typedef statement above on, I'll just stop here and let you
      approach the problem anew based on this info.

      Good luck,
      -leor


      Comment

      • Al Bowers

        #4
        Re: structs help



        Dave Cooke wrote:[color=blue]
        > Hi I am very new to C. I am trying to figure out how to initialize
        > a struct in my main program.
        > The struct is declared in anouther header file like this...
        > typedef struct ln {
        > int key;
        > int data;
        > struct ln *next;
        > } listNode, *listNodePtr;
        >
        > just to test in my main method I tried to initialize the
        > listNodePtr variable to null like this...
        >
        > listNodePtr *head = NULL;[/color]

        The typedef has you confused.
        Here head would be an alias for type
        struct ln **

        What you wnat is
        listNodePtr head;
        [color=blue]
        >
        > First as far as I understand listNode and *listNodePtr are
        > variables of type ln. However I have also learned, so I thought,
        > that listNodePtr is an alias to the struct ln. So my statement
        > above should be legal. Is It?
        >
        > When I try to pass my new listNodePtr variable *head to my
        > listInsert method like........
        >
        > listInsert(head ,1,2);
        >[/color]

        The call would be:
        listInsert(&hea d,1,2)
        [color=blue]
        > it doesn't work. It builds but at run time my program hangs
        > when inside the listInsert method the first if condition
        > tries to determine of the listNodePtr *list is null or not.
        > i.e. if( *list == NULL )..... this is where the program quits.
        >
        > The method definition looks like...
        >
        > void listInsert(list NodePtr *list, int key, int value)
        >[/color]
        This function looks ok except I would change the value type to
        represent success on the Insert.

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

        typedef struct ln {
        int key;
        int data;
        struct ln *next;
        } listNode, *listNodePtr;

        int listInsert( listNodePtr *p, int key, int data);
        void printList(listN odePtr p);
        void freeList(listNo dePtr *p);

        int main(void)
        {
        listNodePtr head = NULL;
        listNode cp = {0}; /* to store a copy of head's values */

        listInsert(&hea d,1,31);
        listInsert(&hea d, 5,45);
        listInsert(&hea d, 6,48);
        printList(head) ;
        if(head != NULL)
        {
        cp = *head;
        freeList(&head) ;
        if(head == NULL) puts("\nAfter freeing head, head = NULL");
        puts("cp has a copy of head's member values");
        printf("cp.key = %d\t\tcp.data = %d\n",cp.key,cp .data);
        }
        return 0;
        }
        int listInsert( listNodePtr *p, int key, int data)
        {
        listNodePtr new;

        new = malloc(sizeof *new);
        if(new == NULL) return 0;
        new->key = key;
        new->data = data;
        new->next = *p;
        *p = new;
        return 1;
        }

        void printList(listN odePtr p)
        {
        size_t i;

        for(i = 1 ; p ; i++, p = p->next)
        printf("%u. key = %d\t\tdata = %d\n",
        i,p->key, p->data);
        return;
        }

        void freeList(listNo dePtr *p)
        {
        listNodePtr tmp;

        for( ; *p ;*p = tmp )
        {
        tmp = (*p)->next;
        free(*p);
        }
        return;
        }



        --
        Al Bowers
        Tampa, Fl USA
        mailto: xabowers@myrapi dsys.com (remove the x to send email)
        Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


        Comment

        • Chris Fogelklou

          #5
          Re: structs help

          > typedef struct In {[color=blue]
          > /* all your member declarations */
          > } In;
          >
          > I used the same name for the typedef as for the structure tag, because
          > that happens to me my own personal style; you might choose to do
          > otherwise, but this is perfectly legal.[/color]

          Although some compilers don't like it (even if it is legal!)

          I've had to go through code written for one compiler and edit all the struct
          definitions for another one because all of the structures defined used the
          same name and the second compiler didn't like it.

          This was for an embedded system... can't remember the specific compiler...
          anyway, for best code portability, use different names:

          typedef my_struct_tag {
          int my_int;
          float my_float;
          } my_struct_t, *p_my_struct_t;

          "Leor Zolman" <leor@bdsoft.co m> wrote in message
          news:kf5v60tim9 5vloilch7r6f9ho jkbhf8tsi@4ax.c om...[color=blue]
          > On Sat, 03 Apr 2004 22:36:05 -0600, Dave Cooke
          > <dcooke@ee.uman itoba.ca> wrote:
          >[color=green]
          > >Hi I am very new to C. I am trying to figure out how to initialize
          > >a struct in my main program.
          > >The struct is declared in anouther header file like this...
          > >typedef struct ln {
          > > int key;
          > > int data;
          > > struct ln *next;
          > >} listNode, *listNodePtr;[/color]
          >
          > The statement above is mixing the "typedef" mechanism with the syntax
          > of declaring and defining structures. The simplest usage of typedef
          > is:
          >
          > typedef some-type identifier;
          >
          > which results in the identifier being another name for the type
          > specified by some-type. If you want to define a struct /instance/
          > named listNode and a pointer to it, you'd simply omit the word
          > "typedef" above and that would be what you'd get (and you wouldn't
          > have any typedefs, so to later define another struct of the same type
          > you'd say:
          > struct In anotherOne;
          > ).
          >
          > If you want to create a typedef (type alias) for a struct of the type
          > you're using, you'd do something like this:
          >
          > typedef struct In {
          > /* all your member declarations */
          > } In;
          >
          > I used the same name for the typedef as for the structure tag, because
          > that happens to me my own personal style; you might choose to do
          > otherwise, but this is perfectly legal.
          >
          > So after that, you could just say:
          >
          > In listNode, *listNodeptr;
          >
          > Because the compiler would have been confused from the point of your
          > original typedef statement above on, I'll just stop here and let you
          > approach the problem anew based on this info.
          >
          > Good luck,
          > -leor
          >
          >[/color]

          Comment

          • Chris Torek

            #6
            Re: structs help

            >"Leor Zolman" <leor@bdsoft.co m> wrote in message[color=blue]
            >news:kf5v60tim 95vloilch7r6f9h ojkbhf8tsi@4ax. com...[color=green]
            >>I used the same name for the typedef as for the structure tag, because
            >>that happens to me my own personal style; you might choose to do
            >>otherwise, but this is perfectly legal.[/color][/color]

            In article <news:byTbc.551 28$mU6.230300@n ewsb.telia.net>
            Chris Fogelklou <chris.fogelklo u@comhem.se> writes:[color=blue]
            >Although some compilers don't like it (even if it is legal!)
            >
            >I've had to go through code written for one compiler and edit all the struct
            >definitions for another one because all of the structures defined used the
            >same name and the second compiler didn't like it.
            >
            >This was for an embedded system... can't remember the specific compiler...[/color]

            The C standards (original ANSI C89, ISO C90, and ISO C99) are quite
            clear: structure tag names are in a separate name space and *must*
            not interfere with any other identifiers in the ordinary name space
            used for variables, functions, and typedef-names. So this particular
            compiler was just plain broken.

            Of course, if you have to use a broken tool, you have to use a
            broken tool. :-) But I would put this next bit differently:
            [color=blue]
            >anyway, for best code portability, use different names:
            >
            >typedef struct my_struct_tag {
            > int my_int;
            > float my_float;
            >} my_struct_t, *p_my_struct_t;[/color]

            As I like to point out, the real problem with typedef is that it
            lies to humans and confuses them.

            First, the keyword itself has the wrong name: it does not define
            a type, but rather changes variable declarations into aliases for
            some existing type(s):

            int a, *b, c[3]; /* declare a as int, *b as int (and thus
            b as pointer to int), c[i] as int (and thus c as array of
            int, with the number of elements in the array being 3) */

            typedef int a, *b, c[3]; /* change the above "declare ... as"
            to "declare ... as an alias for": a is an alias for int,
            b is an alias for pointer-to-int, and c is an alias for
            array-3-of-int. */

            This is even more pronounced in the "typedef struct ..." sequence,
            where people seem to believe that the typedef is creating the new
            type. It is not -- it is the "struct ..." part that creates the
            new type.

            Second, the syntax for using a typedef'ed name is also confusing.
            As I noted in an earlier posting, it becomes impossible to look at
            a code fragment and decide a priori whether something is a declaration:

            int(i),(*p)[3]; /* just to show parentheses in declarations */
            zorgle(blat);

            The second line, which looks like a function call, changes meaning
            if "zorgle" is a typedef:

            typedef char *zorgle;
            ...
            zorgle(blat); /* same as "char *blat; */

            (Of course, if this code appears outside of a function, a function
            call is not allowed here anyway -- at least, not in C. Other languages
            that strongly resemble C *do* allow function calls in such positions.)

            As with macros like:

            #define MIN(a, b) ((a) < (b) ? (a) : (b))

            typedef-names can surprise one if one is not aware that they *are*
            typedef-names, so it is often wise to choose some marker to say
            "beware, this is a typedef-name" -- just as many C programmers
            write the MIN macro above in uppercase, to let other programmers
            know that:

            i = MIN(read_input( ), x++);

            is unlikely to do anything good.

            The "typedef suffix" _t in Chris Fogelklou's examples is just such
            a marker. If one uses it consistently, one can recognize:

            zorgle_t (blat);

            as a declaration (with unnecessary parentheses) without having to
            go look to see whether zorgle_t is in fact a typedef. The _t suffix
            tells you that it must be. (If it is not, the code is simply wrong
            and needs to be fixed.)

            My own preferred method is to type out the keyword "struct" each
            time. I do have one exception to this: if a type-name is going to
            be used heavily within a given program, so that anyone working on
            that program is going to have to be aware that it *is* a type-name,
            then it becomes OK to use a shorter name, even without any special
            syntactic markings (such as an _t suffix or leading uppercase
            letter).

            The idea here is that I expect anyone working on *any* C program
            to know that the C integral types are char, short, int, long, and
            their explicit-sign variants (e.g., signed char and unsigned int),
            the floating point types are float, double, and long double, and
            for C99, the whole series of complex types, and so on. At the same
            time, though, I expect any programmer working on the zorgle program
            to know that the zorgle system uses a "zorgle" type with various
            "semi-abstract datatype" features. If the program happens to use
            some ancillary internal types in places, those might just have to
            spell out the word "struct", and I might even use "struct zorgle"
            anyway for the "well-known" zorgle type -- but because the type is
            pervasive, it is OK to relax the "spell out the struct keyword"
            rule.

            This is, of course, a matter of taste. C *compilers* can keep
            straight which identifiers have been typedef-aliased; whether you,
            as a C programmer, choose some set(s) of rule(s) to make sure
            that mere humans can also keep them straight is up to you.
            --
            In-Real-Life: Chris Torek, Wind River Systems
            Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
            email: forget about it http://web.torek.net/torek/index.html
            Reading email is like searching for food in the garbage, thanks to spammers.

            Comment

            • Leor Zolman

              #7
              Re: structs help

              On 4 Apr 2004 15:42:17 GMT, Chris Torek <nospam@torek.n et> wrote:

              [snipped wonderful essay on pros and cons of using typedef]

              Thanks, Chris, that was really good. I've even got a title for you, in case
              we find a place to publish that (it ought to be required reading for anyone
              starting to use typedef):

              "typedef Considered Harmful - Unless..."

              -leor

              --
              Leor Zolman --- BD Software --- www.bdsoft.com
              On-Site Training in C/C++, Java, Perl and Unix
              C++ users: Download BD Software's free STL Error Message Decryptor at:
              An STL Error Decryptor for C++ by Leor Zolman of BD Software - available to download here

              Comment

              • Barry Schwarz

                #8
                Re: structs help

                On Sat, 03 Apr 2004 22:36:05 -0600, Dave Cooke
                <dcooke@ee.uman itoba.ca> wrote:
                [color=blue]
                >Hi I am very new to C. I am trying to figure out how to initialize
                >a struct in my main program.
                >The struct is declared in anouther header file like this...
                >typedef struct ln {
                > int key;
                > int data;
                > struct ln *next;
                >} listNode, *listNodePtr;
                >
                >just to test in my main method I tried to initialize the[/color]

                C does not have methods. It has functions.
                [color=blue]
                >listNodePtr variable to null like this...
                >
                >listNodePtr *head = NULL;
                >
                >First as far as I understand listNode and *listNodePtr are
                >variables of type ln. However I have also learned, so I thought,[/color]

                No. No neither is a variable. listNode is a typedef (a type alias)
                for the type struct ln. listNodePtr is an alias for the type struct
                ln*. *listNodePtr is exactly the same type as listNode.
                [color=blue]
                >that listNodePtr is an alias to the struct ln. So my statement[/color]

                No, as noted above, it is an alias to the type struct ln*.
                [color=blue]
                >above should be legal. Is It?[/color]

                Yes it is legal. (Your compiler did not generate a syntax error, did
                it?) head has type struct ln** or pointer to pointer to struct ln.
                Is it what you want? We can't tell; you did not show us the code that
                uses it. Post a compilable program that exhibits the behavior you are
                asking about.
                [color=blue]
                >
                >When I try to pass my new listNodePtr variable *head to my
                >listInsert method like........
                >
                >listInsert(hea d,1,2);
                >
                >it doesn't work. It builds but at run time my program hangs[/color]

                It either builds or it hangs. I have yet to see a program do both.
                [color=blue]
                >when inside the listInsert method the first if condition
                >tries to determine of the listNodePtr *list is null or not.
                >i.e. if( *list == NULL )..... this is where the program quits.[/color]

                Does it quit or does it hang?

                From what little code you have shown, this invokes undefined behavior.
                The variable head in main is passed as an argument to listInsert,
                corresponding to the parameter list. Both have the type struct ln**.
                head is initialized to NULL. Therefore, this is the value assigned to
                list at entry to listInsert. Your code attempts to dereference list
                (that is what *list means). You are not allowed to dereference a NULL
                pointer.

                Your comment says you want to determine if list is NULL. You do that
                with
                if (list == NULL) ...
                [color=blue]
                >
                >The method definition looks like...
                >
                >void listInsert(list NodePtr *list, int key, int value)[/color]

                Since C passes by value, how do you expect the results of this
                function to be available to the calling function. Anything you do to
                list will disappear as soon as listInsert returns.
                [color=blue]
                >
                >I am assuming the body of the method is correct as this code
                >was given to us to use by my Prof.
                >
                >Please help what am I doing wrong during my initialization?
                >How do I use structs defined like the one above?[/color]

                Your post indicates some misconceptions about C. Some may be
                considered simply semantic (methods vs functions). Others seem to be
                more basic, such as pointer syntax.

                When you declare a pointer (or typedef a pointer type), you use
                the asterisk to indicate the variable or type is a pointer. When you
                evaluate a pointer variable in your code, you do not use the asterisk
                because in that context the asterisk means dereference the pointer.

                As others have mentioned, using typedef to create a pointer alias
                is strongly not recommended.

                Functions that manipulate linked lists usually use the return type to
                send information back to the calling function. If you set the return
                type of listInsert to struct ln* (or the equivalent listNode*), you
                could then change head and list to this type and return list from the
                listInsert.

                If you really want to use pointer to pointer in listInsert (there are
                times when this may be desirable), you should change head but pass
                &head as the argument. list will still be a struct ln** but:

                When you evaluate list, you get the address of head, not the
                contents of head.

                When you dereference list with *list, you are no longer attempting
                to dereference a NULL pointer. list points to head and when you
                dereference list you get the value in head which is NULL which makes
                your if statement correct.


                <<Remove the del for email>>

                Comment

                • Dave Cooke

                  #9
                  Re: structs help

                  On Sun, 04 Apr 2004 07:33:12 -0400, Al Bowers wrote:
                  [color=blue]
                  >
                  >
                  > Dave Cooke wrote:[color=green]
                  >> Hi I am very new to C. I am trying to figure out how to initialize
                  >> a struct in my main program.
                  >> The struct is declared in anouther header file like this...
                  >> typedef struct ln {
                  >> int key;
                  >> int data;
                  >> struct ln *next;
                  >> } listNode, *listNodePtr;
                  >>
                  >> just to test in my main method I tried to initialize the
                  >> listNodePtr variable to null like this...
                  >>
                  >> listNodePtr *head = NULL;[/color]
                  >
                  > The typedef has you confused.
                  > Here head would be an alias for type
                  > struct ln **
                  >
                  > What you wnat is
                  > listNodePtr head;
                  >[color=green]
                  >>
                  >> First as far as I understand listNode and *listNodePtr are
                  >> variables of type ln. However I have also learned, so I thought,
                  >> that listNodePtr is an alias to the struct ln. So my statement
                  >> above should be legal. Is It?
                  >>
                  >> When I try to pass my new listNodePtr variable *head to my
                  >> listInsert method like........
                  >>
                  >> listInsert(head ,1,2);
                  >>[/color]
                  >
                  > The call would be:
                  > listInsert(&hea d,1,2)
                  >[color=green]
                  >> it doesn't work. It builds but at run time my program hangs
                  >> when inside the listInsert method the first if condition
                  >> tries to determine of the listNodePtr *list is null or not.
                  >> i.e. if( *list == NULL )..... this is where the program quits.
                  >>
                  >> The method definition looks like...
                  >>
                  >> void listInsert(list NodePtr *list, int key, int value)
                  >>[/color]
                  > This function looks ok except I would change the value type to
                  > represent success on the Insert.
                  >
                  > Example:
                  > #include <stdlib.h>
                  > #include <stdio.h>
                  >
                  > typedef struct ln {
                  > int key;
                  > int data;
                  > struct ln *next;
                  > } listNode, *listNodePtr;
                  >
                  > int listInsert( listNodePtr *p, int key, int data);
                  > void printList(listN odePtr p);
                  > void freeList(listNo dePtr *p);
                  >
                  > int main(void)
                  > {
                  > listNodePtr head = NULL;
                  > listNode cp = {0}; /* to store a copy of head's values */
                  >
                  > listInsert(&hea d,1,31);
                  > listInsert(&hea d, 5,45);
                  > listInsert(&hea d, 6,48);
                  > printList(head) ;
                  > if(head != NULL)
                  > {
                  > cp = *head;
                  > freeList(&head) ;
                  > if(head == NULL) puts("\nAfter freeing head, head = NULL");
                  > puts("cp has a copy of head's member values");
                  > printf("cp.key = %d\t\tcp.data = %d\n",cp.key,cp .data);
                  > }
                  > return 0;
                  > }
                  > int listInsert( listNodePtr *p, int key, int data)
                  > {
                  > listNodePtr new;
                  >
                  > new = malloc(sizeof *new);
                  > if(new == NULL) return 0;
                  > new->key = key;
                  > new->data = data;
                  > new->next = *p;
                  > *p = new;
                  > return 1;
                  > }
                  >
                  > void printList(listN odePtr p)
                  > {
                  > size_t i;
                  >
                  > for(i = 1 ; p ; i++, p = p->next)
                  > printf("%u. key = %d\t\tdata = %d\n",
                  > i,p->key, p->data);
                  > return;
                  > }
                  >
                  > void freeList(listNo dePtr *p)
                  > {
                  > listNodePtr tmp;
                  >
                  > for( ; *p ;*p = tmp )
                  > {
                  > tmp = (*p)->next;
                  > free(*p);
                  > }
                  > return;
                  > }[/color]

                  Sorry for not getting back to you guys,
                  WOW a night full of headache's is gone!
                  .....sort of...I guess I just will have to
                  create new ones!.

                  Thanks for the code examples. I am soooo
                  used to Java and C++. C++ I have to manage
                  pointers but C is sooo much different.

                  Thanks for the tip on the return type for the
                  "functions" :). It makes perfect sense.

                  Its frustrating when you have your algorithm worked
                  out on paper but you can't implement it cause you
                  don't know the language you are supposed to use!

                  You saved my lots of time thanks again.

                  Dave






                  Comment

                  • Dave Cooke

                    #10
                    Re: structs help

                    On Sun, 04 Apr 2004 16:41:47 +0000, Leor Zolman wrote:
                    [color=blue]
                    > On 4 Apr 2004 15:42:17 GMT, Chris Torek <nospam@torek.n et> wrote:
                    >
                    > [snipped wonderful essay on pros and cons of using typedef]
                    >
                    > Thanks, Chris, that was really good. I've even got a title for you, in case
                    > we find a place to publish that (it ought to be required reading for anyone
                    > starting to use typedef):
                    >
                    > "typedef Considered Harmful - Unless..."
                    >
                    > -leor[/color]

                    Thanks Chris and Leor for the clarification. It has helped,
                    de-confuse this human....at least a little anyway.
                    Now on to the next confusing part trying to build a "simple"
                    memory manager for my next "AND LAST!" assignment :).

                    Thanks again.

                    Dave

                    Comment

                    • Al Bowers

                      #11
                      Re: structs help



                      Barry Schwarz wrote:[color=blue]
                      > On Sat, 03 Apr 2004 22:36:05 -0600, Dave Cooke
                      > <dcooke@ee.uman itoba.ca> wrote:
                      >
                      >[color=green]
                      >>Hi I am very new to C. I am trying to figure out how to initialize
                      >>a struct in my main program.
                      >>The struct is declared in anouther header file like this...
                      >>typedef struct ln {
                      >> int key;
                      >> int data;
                      >> struct ln *next;
                      >>} listNode, *listNodePtr;
                      >>
                      >>just to test in my main method I tried to initialize the[/color]
                      >
                      >
                      > C does not have methods. It has functions.
                      >
                      >[color=green]
                      >>listNodePtr variable to null like this...
                      >>
                      >>listNodePtr *head = NULL;[/color][/color]

                      I suspect the OP wants:
                      listNodePtr head = NULL;

                      [color=blue][color=green]
                      >>When I try to pass my new listNodePtr variable *head to my
                      >>listInsert method like........
                      >>
                      >>listInsert(he ad,1,2);[/color][/color]

                      The call:
                      listInsert(&hea d,1,2);[color=blue][color=green]
                      >>[/color][/color]
                      [color=blue]
                      >[color=green]
                      >>The method definition looks like...
                      >>
                      >>void listInsert(list NodePtr *list, int key, int value)[/color]
                      >
                      >
                      > Since C passes by value, how do you expect the results of this
                      > function to be available to the calling function. Anything you do to
                      > list will disappear as soon as listInsert returns.
                      >
                      >[/color]

                      Actually this prototype looks correct. It can modify a variable
                      in the calling function.
                      For example in the following, the value of head will be modified
                      should the function listInsert successfully allocate storage.

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

                      typedef struct ln {
                      int key;
                      int data;
                      struct ln *next;
                      } listNode, *listNodePtr;

                      void listInsert( listNodePtr *p, int key, int data);

                      int main(void)
                      {
                      listNodePtr head = NULL;

                      printf("In Main: Before call to listInsert function head"
                      " is %sNULL\n", head?"not ":"");
                      listInsert(&hea d,1,31);
                      printf("In Main: After call to listInsert function head"
                      " is %sNULL\n", head?"not ":"");
                      free(head);
                      return 0;
                      }
                      void listInsert( listNodePtr *p, int key, int data)
                      {
                      listNodePtr new;

                      new = malloc(sizeof *new);
                      if(new != NULL)
                      {
                      new->key = key;
                      new->data = data;
                      new->next = *p;
                      *p = new;
                      }
                      return;
                      }

                      --
                      Al Bowers
                      Tampa, Fl USA
                      mailto: xabowers@myrapi dsys.com (remove the x to send email)
                      Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


                      Comment

                      • Barry Schwarz

                        #12
                        Re: structs help

                        On Sun, 04 Apr 2004 21:00:09 -0400, Al Bowers <xabowers@rapid sys.com>
                        wrote:
                        [color=blue]
                        >Barry Schwarz wrote:[color=green]
                        >> On Sat, 03 Apr 2004 22:36:05 -0600, Dave Cooke
                        >> <dcooke@ee.uman itoba.ca> wrote:
                        >>
                        >>[color=darkred]
                        >>>Hi I am very new to C. I am trying to figure out how to initialize
                        >>>a struct in my main program.
                        >>>The struct is declared in anouther header file like this...
                        >>>typedef struct ln {
                        >>> int key;
                        >>> int data;
                        >>> struct ln *next;
                        >>>} listNode, *listNodePtr;
                        >>>
                        >>>just to test in my main method I tried to initialize the[/color]
                        >>
                        >>
                        >> C does not have methods. It has functions.
                        >>
                        >>[color=darkred]
                        >>>listNodePt r variable to null like this...
                        >>>
                        >>>listNodePt r *head = NULL;[/color][/color]
                        >
                        >I suspect the OP wants:
                        >listNodePtr head = NULL;
                        >
                        >[color=green][color=darkred]
                        >>>When I try to pass my new listNodePtr variable *head to my
                        >>>listInsert method like........
                        >>>
                        >>>listInsert(h ead,1,2);[/color][/color]
                        >
                        >The call:
                        >listInsert(&he ad,1,2);[color=green][color=darkred]
                        >>>[/color][/color]
                        >[color=green]
                        >>[color=darkred]
                        >>>The method definition looks like...
                        >>>
                        >>>void listInsert(list NodePtr *list, int key, int value)[/color]
                        >>
                        >>
                        >> Since C passes by value, how do you expect the results of this
                        >> function to be available to the calling function. Anything you do to
                        >> list will disappear as soon as listInsert returns.
                        >>
                        >>[/color]
                        >
                        >Actually this prototype looks correct. It can modify a variable
                        >in the calling function.[/color]

                        Of course it can but only if the argument is of the form &variable or
                        equivalent. The OP's argument wasn't and therefore it couldn't. All
                        of which was covered in the subsequent paragraphs of my response which
                        you chose to omit.


                        <<Remove the del for email>>

                        Comment

                        Working...