dynamic declaration of struct array

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

    dynamic declaration of struct array

    Why won't the declaration of a struct array work if I do it like this:

    1 typedef struct
    2 {
    3 int pens;
    4 int pencils;
    5 } Stationers;
    6

    .........

    7 int main(void)
    8 {
    9 int num;

    ...........num defined in code........

    10
    11 Stationers stats[num];
    12 }

    The error message says "constant expression required" and highlights
    line 11. I want to declare it dynamically during runtime, could
    someone explain how to do this please.
  • Noah Roberts

    #2
    Re: dynamic declaration of struct array

    Tim wrote:
    Stationers stats[num];[color=blue]
    > 12 }
    >
    > The error message says "constant expression required" and highlights
    > line 11. I want to declare it dynamically during runtime, could
    > someone explain how to do this please.[/color]

    Stationers *stats = (Stationers*)ma lloc(num * sizeof(Statione rs));

    NR

    Comment

    • Ivan Vecerina

      #3
      Re: dynamic declaration of struct array

      "Tim" <hillbilly010@y ahoo.co.uk> wrote in message
      news:add027e8.0 310101317.48cef ae5@posting.goo gle.com...[color=blue]
      > Why won't the declaration of a struct array work if I do it like this:[/color]
      ....[color=blue]
      > 7 int main(void)
      > 8 {
      > 9 int num;
      >
      > ...........num defined in code........
      >
      > 10
      > 11 Stationers stats[num];
      > 12 }
      >
      > The error message says "constant expression required" and highlights
      > line 11. I want to declare it dynamically during runtime, could
      > someone explain how to do this please.[/color]

      This code is actually valid if your compiler implements the 1999
      C standard. Prior to that, array variables are indeed required
      to be of a size known at compile time.

      The backwards-compatible way to do what you want is to use:
      Stationers* stats = (Stationers*)ma lloc(num*sizeof (Stationers));
      ... use stats as if it were an array of size num ...
      free(stats); // don't forget this prior to exit !


      Hope this helps,
      Ivan
      --
      Ivan Vecerina - expert in medical devices, software - info, links, contact information, code snippets





      Comment

      • Dave Vandervies

        #4
        Re: dynamic declaration of struct array

        In article <add027e8.03101 01317.48cefae5@ posting.google. com>,
        Tim <hillbilly010@y ahoo.co.uk> wrote:[color=blue]
        >Why won't the declaration of a struct array work if I do it like this:[/color]

        [snip struct definition]
        [color=blue]
        >7 int main(void)
        >8 {
        >9 int num;
        >
        > ...........num defined in code........
        >
        >10
        >11 Stationers stats[num];
        >12 }
        >
        >The error message says "constant expression required" and highlights
        >line 11. I want to declare it dynamically during runtime, could
        >someone explain how to do this please.[/color]

        Uhmm... what language are you trying to write this code in?

        If you're using C99, what you have here should work, since arrays are
        allowed to have lengths that aren't known until run-time.

        If you're using C90, you're not allowed to declare a new variable (like
        the array) after non-declaration stuff (like assigning a value to num),
        so once you fill in the blanks your code will still be broken no matter
        how you declare the array. Instead, you'd need to declare a pointer at
        the beginning of the block and, once you've decided how many elements
        you want, use malloc to allocate memory for it:
        --------
        #include <stdlib.h>

        /*Define and typedef the Stationers struct here*/

        int main(void)
        {
        int num;
        Stationers *stats;

        /*Decide on a value for num here*/

        stats=malloc(nu m * sizeof *stats);

        /*I assume you'll want to do something with stats here*/

        free(stats);
        }
        --------

        If you're using C++ (which also allows declarations after non-
        declarations), go to comp.lang.c++ and ask about (or, better, open a
        textbook and read about) new[] and std::vector.


        dave

        --
        Dave Vandervies dj3vande@csclub .uwaterloo.ca
        So "Patterns" are really just another name for "Object-oriented programming",
        which is really just another name for "Structured programming", which is really
        just big words for "good hacking". --Richard Bos in comp.lang.c

        Comment

        • Irrwahn Grausewitz

          #5
          Re: dynamic declaration of struct array

          hillbilly010@ya hoo.co.uk (Tim) wrote:
          [color=blue]
          >Why won't the declaration of a struct array work if I do it like this:
          >
          >1 typedef struct
          >2 {
          >3 int pens;
          >4 int pencils;
          >5 } Stationers;
          >6
          >
          > .........
          >
          >7 int main(void)
          >8 {
          >9 int num;
          >
          > ...........num defined in code........
          >
          >10
          >11 Stationers stats[num];
          >12 }
          >
          >The error message says "constant expression required" and highlights
          >line 11. I want to declare it dynamically during runtime, could
          >someone explain how to do this please.[/color]

          Yes, you have to define a pointer and dynamically allocate memory for
          it to point to, look:

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

          typedef
          struct
          {
          int pens;
          int pencils;
          }
          Stationers;

          int main( void )
          {
          int num;
          Stationers *stats;

          /* calculate value for num, e.g: */
          num = 42;

          stats = malloc( num * sizeof *stats );
          if ( stats == NULL )
          {
          fprintf( stderr, "Memory allocation error." );
          return EXIT_FAILURE;
          }

          /* do something with stats, e.g: */
          stats[ 7 ].pens = 6;
          stats[ 7 ].pencils = 9;

          return EXIT_SUCCESS;
          }

          Regards
          --
          Irrwahn
          (irrwahn33@free net.de)

          Comment

          • Irrwahn Grausewitz

            #6
            Re: dynamic declaration of struct array

            dj3vande@csclub .uwaterloo.ca (Dave Vandervies) wrote:
            [color=blue]
            >Tim <hillbilly010@y ahoo.co.uk> wrote:[/color]
            <SNIP>[color=blue][color=green]
            >>7 int main(void)
            >>8 {
            >>9 int num;
            >>
            >> ...........num defined in code........
            >>
            >>10
            >>11 Stationers stats[num];
            >>12 }
            >>
            >>The error message says "constant expression required" and highlights
            >>line 11. I want to declare it dynamically during runtime, could
            >>someone explain how to do this please.[/color]
            >
            >Uhmm... what language are you trying to write this code in?
            >
            >If you're using C99, what you have here should work, since arrays are
            >allowed to have lengths that aren't known until run-time.
            >
            >If you're using C90, you're not allowed to declare a new variable (like
            >the array) after non-declaration stuff (like assigning a value to num),
            >so once you fill in the blanks your code will still be broken no matter
            >how you declare the array. Instead, you'd need to declare a pointer at
            >the beginning of the block and, once you've decided how many elements
            >you want, use malloc to allocate memory for it:
            >--------
            >#include <stdlib.h>
            >
            >/*Define and typedef the Stationers struct here*/
            >
            >int main(void)
            >{
            > int num;
            > Stationers *stats;
            >
            > /*Decide on a value for num here*/
            >
            > stats=malloc(nu m * sizeof *stats);[/color]
            /* check malloc() return value here! */[color=blue]
            >
            > /*I assume you'll want to do something with stats here*/
            >
            > free(stats);[/color]
            return 0;[color=blue]
            >}[/color]
            <SNIP>
            --
            Irrwahn
            (irrwahn33@free net.de)

            Comment

            • Irrwahn Grausewitz

              #7
              Re: dynamic declaration of struct array

              Noah Roberts <nroberts@donte mailme.com> wrote:
              [color=blue]
              >Tim wrote:[/color]
              [ some code restored ... ][color=blue][color=green]
              >> 7 int main(void)
              >> 8 {
              >> 9 int num;
              >> ...........num defined in code........
              >> 10
              >> 11 Stationers stats[num];
              >> 12 }
              >>
              >> The error message says "constant expression required" and highlights
              >> line 11. I want to declare it dynamically during runtime, could
              >> someone explain how to do this please.[/color]
              >
              >Stationers *stats = (Stationers*)ma lloc(num * sizeof(Statione rs));[/color]

              Better:

              Stationers *stats = malloc(num * sizeof *stats);

              (The cast to is not only unnecessary, it may hide the failure of not
              including stdlib.h; sizeof *stats has the advantage that one does not
              have to change the malloc expression if the type of stats ever changes.)

              But still this won't work in pre-C99 (in this special case): you define
              a variable in another place than the beginning of a block. Or, if you
              intended to put above line at the top of main(), you don't know the
              value for num, as it has to be calculated yet.

              So, there's no way around splitting the line up into:

              /* goes to top of main(): */
              Stationers *stats;

              /* after num has been calculated: */
              stats = malloc(num * sizeof *stats);

              Regards
              --
              Irrwahn
              (irrwahn33@free net.de)

              Comment

              • Irrwahn Grausewitz

                #8
                Re: dynamic declaration of struct array

                "Ivan Vecerina" <ivecATmyrealbo xDOTcom> wrote:
                [color=blue]
                >"Tim" <hillbilly010@y ahoo.co.uk> wrote in message
                >news:add027e8. 0310101317.48ce fae5@posting.go ogle.com...[color=green]
                >> Why won't the declaration of a struct array work if I do it like this:[/color]
                >...[color=green]
                >> 7 int main(void)
                >> 8 {
                >> 9 int num;
                >>
                >> ...........num defined in code........
                >>
                >> 10
                >> 11 Stationers stats[num];
                >> 12 }
                >>
                >> The error message says "constant expression required" and highlights
                >> line 11. I want to declare it dynamically during runtime, could
                >> someone explain how to do this please.[/color]
                >
                >This code is actually valid if your compiler implements the 1999
                >C standard. Prior to that, array variables are indeed required
                >to be of a size known at compile time.
                >
                >The backwards-compatible way to do what you want is to use:
                > Stationers* stats = (Stationers*)ma lloc(num*sizeof (Stationers));[/color]

                Better:

                Stationers *stats = malloc(num * sizeof *stats);

                (The cast is not only unnecessary, it may hide the failure of not
                including stdlib.h; sizeof *stats has the advantage that one does not
                have to change the malloc expression if the type of stats ever changes.)

                But still this won't work in pre-C99 (in this special case): you define
                a variable in another place than the beginning of a block. Or, if you
                intended to put above line at the top of main(), you don't know the
                value for num, as it has to be calculated yet.

                So, there's no way around splitting the line up into:

                /* goes to top of main(): */
                Stationers *stats;

                /* after num has been calculated: */
                stats = malloc(num * sizeof *stats);
                [color=blue]
                > ... use stats as if it were an array of size num ...
                > free(stats); // don't forget this prior to exit !
                >[/color]

                Regards
                --
                Irrwahn
                (irrwahn33@free net.de)

                Comment

                • Ivan Vecerina

                  #9
                  Re: dynamic declaration of struct array

                  "Irrwahn Grausewitz" <irrwahn33@free net.de> wrote in message
                  news:laaeovkvbt dmv1u6kn0ao72c1 bdg1f0vu7@4ax.c om...[color=blue]
                  > int main( void )
                  > {
                  > int num;
                  > Stationers *stats;
                  >
                  > /* calculate value for num, e.g: */
                  > num = 42;
                  >
                  > stats = malloc( num * sizeof *stats );
                  > if ( stats == NULL )
                  > {
                  > fprintf( stderr, "Memory allocation error." );
                  > return EXIT_FAILURE;
                  > }
                  >
                  > /* do something with stats, e.g: */
                  > stats[ 7 ].pens = 6;
                  > stats[ 7 ].pencils = 9;[/color]

                  add:
                  free( stats );
                  [color=blue]
                  > return EXIT_SUCCESS;
                  > }[/color]

                  Yes, the memory will be reclaimed at program exit on
                  any decent OS, but it is a good habit to always free
                  the memory that you allocate. (e.g. in case the code
                  gets moved into a loop or another function...).

                  Cheers,
                  Ivan
                  --
                  Ivan Vecerina - expert in medical devices, software - info, links, contact information, code snippets



                  Comment

                  • Irrwahn Grausewitz

                    #10
                    Re: dynamic declaration of struct array

                    "Ivan Vecerina" <ivecATmyrealbo xDOTcom> wrote:
                    [color=blue]
                    >"Irrwahn Grausewitz" <irrwahn33@free net.de> wrote in message
                    >news:laaeovkvb tdmv1u6kn0ao72c 1bdg1f0vu7@4ax. com...[color=green]
                    >> int main( void )
                    >> {
                    >> int num;
                    >> Stationers *stats;
                    >>
                    >> /* calculate value for num, e.g: */
                    >> num = 42;
                    >>
                    >> stats = malloc( num * sizeof *stats );
                    >> if ( stats == NULL )
                    >> {
                    >> fprintf( stderr, "Memory allocation error." );
                    >> return EXIT_FAILURE;
                    >> }
                    >>
                    >> /* do something with stats, e.g: */
                    >> stats[ 7 ].pens = 6;
                    >> stats[ 7 ].pencils = 9;[/color]
                    >
                    >add:
                    > free( stats );
                    >[color=green]
                    >> return EXIT_SUCCESS;
                    >> }[/color]
                    >
                    >Yes, the memory will be reclaimed at program exit on
                    >any decent OS, but it is a good habit to always free
                    >the memory that you allocate. (e.g. in case the code
                    >gets moved into a loop or another function...).[/color]

                    Good point.
                    [color=blue]
                    >
                    >Cheers,
                    >Ivan[/color]

                    Regards
                    --
                    Irrwahn
                    (irrwahn33@free net.de)

                    Comment

                    • Allin Cottrell

                      #11
                      Re: dynamic declaration of struct array

                      Noah Roberts wrote:[color=blue]
                      > Tim wrote:
                      > Stationers stats[num];
                      >[color=green]
                      >> 12 }
                      >>
                      >> The error message says "constant expression required" and highlights
                      >> line 11. I want to declare it dynamically during runtime, could
                      >> someone explain how to do this please.[/color]
                      >
                      >
                      > Stationers *stats = (Stationers*)ma lloc(num * sizeof(Statione rs));[/color]

                      Or, better (losing the spurious cast):

                      Stationers *stats = malloc(num * sizeof *stats);

                      --
                      Allin Cottrell
                      Department of Economics
                      Wake Forest University, NC

                      Comment

                      • Tim

                        #12
                        Re: dynamic declaration of struct array

                        Cheers for the help, I'm now using the malloc function and its working well.
                        Tim.

                        Comment

                        Working...