Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

can't assign null to struct pointer variable

Help
steven
2008-11-22
2013-03-12
  • steven
    steven
    2008-11-22

    Example :

    #define NULL 0

    typedef struct
    {
    int i;
    char c;
    } someStructType;

    someStructType *struct1, struct2;
    void main
    {
    struct1 = NULL;  // can't pass compile here
    }

    please help me, thanks.

     
    • Maarten Brock
      Maarten Brock
      2008-11-22

      NULL is defined in <stddef.h>. You should not define it yourself.

       
    • steven
      steven
      2008-11-23

      maartenbrock, thank you for your reply. But I can't initial struct pointer variant to zero too.

      Example:

      typedef struct 

      int i; 
      char c; 
      } someStructType; 

      someStructType *struct1, struct2; 
      void main 

      struct1 = 0; // can't pass compile here
      }

      How can i intial struct1 to null pointer?

       
      • Raphael Neider
        Raphael Neider
        2008-11-23

        Try using a correct funcion declarator for main:

        typedef struct
        {
        int i;
        char c;
        } someStructType;

        someStructType *struct1, /* want a `*` here too? */ struct2;
        void main (void) /* <-- FIXED */
        {
        struct1 = 0; /* works */
        struct1 = (void *)0; /* works as well */
        struct1 = (someStructType *)0; /* works too */
        }

        If struct2 is to be another pointer to a someStructType, you need an additional * where indicated. Otherwise struct2 is an instance of the struct.

        Tested with sdcc 2.8.5 from svn r5273.

        Hope that helps,
        Raphael

         
        • Maarten Brock
          Maarten Brock
          2008-11-24

          struct1 = 0; /* works */

          No, this does not always work with SDCC. That's why I said to use NULL from <stddef.h>. It has:
          #define NULL (void*)0

          On devices with Harvard architecture like the mcs51 all pointer constants must be cast to a pointer type with a storage class (generic or other). From the value alone the compiler cannot guess which memory it should point to.

          Maarten

           
    • steven
      steven
      2008-11-23

      thanks, you are very nice. I will update too the latest version.