Thread: initializing structure variables

  1. #1
    Registered User
    Join Date
    Jan 2008

    initializing structure variables

    Given the following code:

    #include <stdio.h>
    #include <stdlib.h>
    typedef struct foo {
      int test;
      char b;
    } foo;
    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
    Farncombe, Surrey, England
    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").

    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

    Struct Definition

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

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

    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, 11:07 PM
  3. passing structure arrays to functions?
    By bem82 in forum C Programming
    Replies: 3
    Last Post: 10-30-2006, 06: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, 12:19 PM