2D array of structures

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

    #1

    2D array of structures

    Hello,

    I wonder how to resize such array of structures using realloc()?

    #include <stdio.h>
    #include <stdlib.h>
    #define FIRST 7

    typedef struct {
    char *name;
    int i;
    int j;
    } STRUCTURE;

    STRUCTURE **p_structure;

    int main() {

    p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
    if ( p_structure == NULL ) {
    printf("Failed to allocate memory, exiting...");
    return 1;
    }
    }

    Thank you in advance

    Svata

  • Jens Thoms Toerring

    #2
    Re: 2D array of structures

    svata <svatoboj@centr um.czwrote:
    I wonder how to resize such array of structures using realloc()?
    #include <stdio.h>
    #include <stdlib.h>
    #define FIRST 7
    typedef struct {
    char *name;
    int i;
    int j;
    } STRUCTURE;
    STRUCTURE **p_structure;
    int main() {
    Make that

    int main( void )

    since your main() takes no arguments.
    p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
    Don't cast the return value of malloc(), it only hides your mistake
    should you have forgotten to include <stdlib.h>. But, more important,
    you allocate here memory for 7 (FIRST) such structures. malloc() returns
    a pointer to the start of this memory, which is of type 'STRUCTURE *'
    (malloc() actually returns a void pointer but "STRUCTURE *' is the
    correct type of a pointer to that memory). But you assign it instead
    to a pointer that has type 'STRUCTURE **'. That, combined with your
    use of the words "2D array" in the subjct line, leads to the suspicion
    that you actually don't want to allocate memory for something that has
    similar properties as an array of stuctures, but something more compli-
    cated and similar to a 2D array of such structures. And that's what you
    definitely won't get with that allocation, whatever the type of the
    pointer you assign the return value of malloc() to. So, instead of
    starting to guess what you might have intended I think it's better to
    ask you to specify a bit more clearly what you intend to do here: do
    you just want memory for a simple set of structures or do you want
    something like a 2D array of such structures. In the first case you
    could "repair" your program by simply defining 'p_structure' as

    STTRUCTURE *p_structure;

    Perhaps you thenn also might want to replace the line for the allo-
    cation by

    p_structure = malloc(FIRST * sizeof *p_structure);

    because that way you don't have to change that line anymore if you
    should decide to change the type of 'p_structure' sometime later.

    You also write something about realloc() but I can't see any
    use or mentioning of realloc() in the code you posted. But, of
    course, you can use realloc() to resize the amount of memory
    you obtained from malloc() - that's what realloc() was invented
    for.
    if ( p_structure == NULL ) {
    printf("Failed to allocate memory, exiting...");
    return 1;
    }
    It's good to see that you check that what malloc() returned!
    }
    Since main() returns an int, here's a missing line with a return
    value...
    Regards, Jens
    --
    \ Jens Thoms Toerring ___ jt@toerring.de
    \______________ ____________ http://toerring.de

    Comment

    • Flash Gordon

      #3
      Re: 2D array of structures

      Jens Thoms Toerring wrote:
      svata <svatoboj@centr um.czwrote:
      <snip>
      >p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
      <snip>
      correct type of a pointer to that memory). But you assign it instead
      to a pointer that has type 'STRUCTURE **'. That, combined with your
      use of the words "2D array" in the subjct line, leads to the suspicion
      that you actually don't want to allocate memory for something that has
      similar properties as an array of stuctures, but something more compli-
      cated and similar to a 2D array of such structures. And that's what you
      <snip>

      I agree with what you've said, but the OP should also read section 6 of
      the comp.lang.c FAQ before posting back here. Section 6 includes ways of
      dynamically allocating space for things that work like 2D arrays. The
      FAQ can be found at http://c-faq.com/
      --
      Flash Gordon

      Comment

      • Frederick Gotham

        #4
        Re: 2D array of structures

        svata:
        STRUCTURE **p_structure;

        This is a pointer to a pointer to a STRUCTURE.

        (I'm against the use of ALL CAPS for anything other than macros)

        int main() {
        >
        p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));

        This doesn't make sense.

        You have a pointer to a pointer to a STRUCTURE. This would suggest to me
        that you're going to store either of the following in it:

        (1) The address of a pointer to a STRUCTURE.
        (2) The address of the first element of an array, whereby each element
        is a pointer to a STRUCTURE.

        If it were either of the two above, the "malloc" invocation should look
        something like:

        p_structure = malloc( sizeof(STRUCTUR E*) );
        or:
        p_structure = malloc( 12 * sizeof(STRUCTUR E*) );

        Note that I use the size of a "STRUCTURE* " rather than the size of a
        "STRUCTURE" .

        Of course, it's better to write the two of them as:

        p_structure = malloc(sizeof*p );

        p_structure = malloc(12 * sizeof*p);

        --

        Frederick Gotham

        Comment

        • CBFalconer

          #5
          Re: 2D array of structures

          svata wrote:
          >
          I wonder how to resize such array of structures using realloc()?
          >
          #include <stdio.h>
          #include <stdlib.h>
          #define FIRST 7
          >
          typedef struct {
          char *name;
          int i;
          int j;
          } STRUCTURE;
          >
          STRUCTURE **p_structure;
          Too many *s here.
          >
          int main() {
          You
          >
          p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
          and here. Also _never_ cast the return from malloc (it only hides
          errors without fixing them). You want:

          p_structure = malloc(FIRST * sizeof *p_structure);
          if ( p_structure == NULL ) {
          printf("Failed to allocate memory, exiting...");
          return 1;
          }
          }
          You can then change the size to, say, SECOND with:

          STRUCTURE *tmp; /* in a suitable location, not here */

          if (tmp = realloc(p_struc ture, SECOND) p_structure = tmp;
          else {
          /* handle lack of memory */
          }

          --
          Chuck F (cbfalconer at maineline dot net)
          Available for consulting/temporary embedded and systems.
          <http://cbfalconer.home .att.net>

          Comment

          • svata

            #6
            Re: 2D array of structures

            Hello Frederick,

            I know it doesn't make sense. I was wrong in my assumption.
            I should use p_structure = (STRUCTURE **) malloc(FIRST *
            sizeof(STRUCTUR E*));

            but anyway... should rather use array of structures.


            typedef structure {
            code goes here...
            } _structure;

            _structure *p_structure;
            // and then malloc()

            p_structure = malloc( INT * sizeof(_structu re));

            if am I right?

            svata

            Frederick Gotham wrote:
            STRUCTURE **p_structure;
            >
            >
            This is a pointer to a pointer to a STRUCTURE.
            >
            (I'm against the use of ALL CAPS for anything other than macros)
            >
            >
            int main() {

            p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
            >
            >
            This doesn't make sense.
            >
            --
            >
            Frederick Gotham

            Comment

            • Chris Dollin

              #7
              Re: 2D array of structures

              svata wrote:
              Hello Frederick,
              >
              I know it doesn't make sense. I was wrong in my assumption.
              I should use p_structure = (STRUCTURE **) malloc(FIRST *
              sizeof(STRUCTUR E*));
              No, you shouldn't: it's wiser to drop the unnecessary cast an
              to ensure that the thing you sizeof is appropriate for the
              pointer:

              pStructure = malloc( FIRST * sizeof (*pStructure) );

              which will (try to) mallocate space for FIRST (horrid name)
              lumps of space adequate for the kinds of thing that
              pStructure points to.
              but anyway... should rather use array of structures.
              Yes, get rid of the unnecessary layer of indirection.
              typedef structure {
              code goes here...
              } _structure;
              There are two things wrong with this. One is that it's
              syntax is broken, since you spelt "struct" "structure" .
              The other is that so many names beginning with _ are
              reserved to the implementation it's unwise for you to
              define /any/ name that does. So don't.

              If you /must/ use a typedef for a structure -- you don't
              need to, and some wise people argue that you shouldn't
              (although others argue that those arguments aren't
              convincing) -- you should also give it a /sensible/
              name. "structure" isn't.

              typedef struct yourStructTagHe re
              {
              int x;
              int y;
              } Point;

              --
              Chris ".enable proofreading" Dollin
              The "good old days" used to be much better.

              Comment

              • svata

                #8
                Re: 2D array of structures

                Chris Dollin wrote:

                I learn by doing. So I will see what results I get.
                pStructure = malloc( FIRST * sizeof (*pStructure) );
                >
                which will (try to) mallocate space for FIRST (horrid name)
                lumps of space adequate for the kinds of thing that
                pStructure points to.
                >
                but anyway... should rather use array of structures.
                >
                Yes, get rid of the unnecessary layer of indirection.
                >
                typedef structure {
                code goes here...
                } _structure;
                >
                There are two things wrong with this. One is that it's
                syntax is broken, since you spelt "struct" "structure" .
                The other is that so many names beginning with _ are
                reserved to the implementation it's unwise for you to
                define /any/ name that does. So don't.
                >
                If you /must/ use a typedef for a structure -- you don't
                need to, and some wise people argue that you shouldn't
                (although others argue that those arguments aren't
                convincing) -- you should also give it a /sensible/
                name. "structure" isn't.
                >
                typedef struct yourStructTagHe re
                {
                int x;
                int y;
                } Point;
                >
                --
                Chris ".enable proofreading" Dollin
                The "good old days" used to be much better.

                Comment

                • svata

                  #9
                  Re: 2D array of structures

                  I always use google to search an answer, but often results are not
                  relevant.


                  svata
                  >
                  I agree with what you've said, but the OP should also read section 6 of
                  the comp.lang.c FAQ before posting back here. Section 6 includes ways of
                  dynamically allocating space for things that work like 2D arrays. The
                  FAQ can be found at http://c-faq.com/
                  --
                  Flash Gordon

                  Comment

                  • Richard Heathfield

                    #10
                    Re: 2D array of structures

                    svata said:
                    Chris Dollin wrote:
                    >
                    I learn by doing. So I will see what results I get.
                    That's fine sometimes, but there are also times when it's best to learn from
                    other people's knowledge and experience. If you learn C "by doing", you're
                    likely to end up doing lots of things that aren't correct, but which happen
                    to behave in a particular way on your current system. Switch systems, and
                    all your code breaks. Oops.

                    Chris is an expert on C. Listen to Chris.

                    --
                    Richard Heathfield
                    "Usenet is a strange place" - dmr 29/7/1999

                    email: normal service will be restored as soon as possible. Please do not
                    adjust your email clients.

                    Comment

                    • CBFalconer

                      #11
                      Re: 2D array of structures

                      svata wrote:
                      >
                      I always use google to search an answer, but often results are not
                      relevant.
                      >
                      >I agree with what you've said, but the OP should also read section
                      >6 of the comp.lang.c FAQ before posting back here. Section 6
                      >includes ways of dynamically allocating space for things that work
                      >like 2D arrays. The FAQ can be found at http://c-faq.com/
                      I'm sure you've been told this before, but DON'T TOP-POST. See the
                      links in my sig below.

                      --
                      Some informative links:
                      <news:news.anno unce.newusers
                      <http://www.geocities.c om/nnqweb/>
                      <http://www.catb.org/~esr/faqs/smart-questions.html>
                      <http://www.caliburn.nl/topposting.html >
                      <http://www.netmeister. org/news/learn2quote.htm l>
                      <http://cfaj.freeshell. org/google/>


                      Comment

                      • Chris Dollin

                        #12
                        Re: 2D array of structures

                        Richard Heathfield wrote:
                        svata said:
                        >
                        >Chris Dollin wrote:
                        >>
                        >I learn by doing. So I will see what results I get.
                        Something happend to your quoting, Richard: it looks like it was me that
                        said "I learn by doing. So I will see what results I get.", but it was
                        svata.

                        (svata's quoting was misleading anyway, since he half-top-posted.)
                        That's fine sometimes, but there are also times when it's best to learn from
                        other people's knowledge and experience. If you learn C "by doing", you're
                        likely to end up doing lots of things that aren't correct, but which happen
                        to behave in a particular way on your current system. Switch systems, and
                        all your code breaks. Oops.
                        >
                        Chris is an expert on C.
                        I'd hesitate to describe myself so, since there's so much C I don't
                        know (most of the C99 stuff, for example!) and I've used it in so
                        few environments. I know /some/ stuff about C. I hope it's useful
                        stuff.
                        Listen to Chris.
                        But not when I'm singing.

                        --
                        Chris "for that, you want Annie, Rachel, Anne-Marie, or Tina." Dollin
                        "Reaching out for mirrors hidden in the web." - Renaissance, /Running Hard/

                        Comment

                        • CBFalconer

                          #13
                          Re: 2D array of structures

                          Chris Dollin wrote:
                          Richard Heathfield wrote:
                          >
                          .... snip ...
                          >
                          >Listen to Chris.
                          >
                          But not when I'm singing.
                          Like me, you appear to be a member of the 'crows in heat' chorus.

                          --
                          Chuck F (cbfalconer at maineline dot net)
                          Available for consulting/temporary embedded and systems.
                          <http://cbfalconer.home .att.net>


                          Comment

                          • Chris Dollin

                            #14
                            Re: 2D array of structures

                            CBFalconer wrote:
                            Chris Dollin wrote:
                            >Richard Heathfield wrote:
                            >>
                            ... snip ...
                            >>
                            >>Listen to Chris.
                            >>
                            >But not when I'm singing.
                            >
                            Like me, you appear to be a member of the 'crows in heat' chorus.
                            Very likely. Or hedgehogs ... snuffling. Perhaps we should
                            characterise Undefined Behaviour as "Chris or <your preferred
                            abbreviationwil l sing for/at you". /That/ will worry them
                            more than hyperbolic nasal demons.

                            --
                            Chris "we are BRO-KEN, without FEE-LING" Dollin
                            "Who do you serve, and who do you trust?" /Crusade/

                            Comment

                            • Richard Heathfield

                              #15
                              Re: 2D array of structures

                              Chris Dollin said:
                              Richard Heathfield wrote:
                              >
                              >svata said:
                              >>
                              >>Chris Dollin wrote:
                              >>>
                              >>I learn by doing. So I will see what results I get.
                              >
                              Something happend to your quoting, Richard:
                              No, just a snip slip. Sorry about that.
                              >Chris is an expert on C.
                              >
                              I'd hesitate to describe myself so,
                              Think "relative". Compared to most OPs around here, you're a towering
                              genius!

                              --
                              Richard Heathfield
                              "Usenet is a strange place" - dmr 29/7/1999

                              email: normal service will be restored as soon as possible. Please do not
                              adjust your email clients.

                              Comment

                              Working...