initializing structure variables

This is a discussion on initializing structure variables within the C Programming forums, part of the General Programming Boards category; Given the following code: Code: #include <stdio.h> #include <stdlib.h> typedef struct foo { int test; char b; } foo; int ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    69

    initializing structure variables

    Given the following code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct foo {
      int test;
      char b;
    } foo;
    
    int
    main(int argc, char *argv[]) {
    
      foo f = {2, 'c'};
      int i = f->test;
      printf("%d\n", i);
    
      return 0;
    }
    Why do I get an error when compiling?

    test.c: In function 'main':
    test.c:13: error: invalid type argument of '->'

    When I use decimal notation, such as f.test, it works fine.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    a->b is the same as (*a).b - since your f is not a pointer, it is not allowed to use ->, but you should use the "dot" notation (I wouldn't call it "decimal", since that's just one usage of "dot/point").

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    12

    Struct Definition

    I think you may have too many "foo"s:

    Code:
    typedef struct foo {
      int test;
      char b;
    } foo;
    Could also be written:

    Code:
    typedef struct {
      int test;
      char b;
    } foo;
    I'm pretty sure that first foo is unnecessary.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  2. esbo's data sharing example
    By esbo in forum C Programming
    Replies: 49
    Last Post: 01-08-2008, 10:07 PM
  3. passing structure arrays to functions?
    By bem82 in forum C Programming
    Replies: 3
    Last Post: 10-30-2006, 05:17 AM
  4. Another Linked List plee
    By Dragoncaster131 in forum C Programming
    Replies: 3
    Last Post: 05-15-2004, 05:40 PM
  5. Initializing variables
    By Stryder_SoZ in forum C++ Programming
    Replies: 4
    Last Post: 11-09-2001, 11:19 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21