sizeof dynamic array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • D@nny

    sizeof dynamic array

    hi,

    i would like to know how to calculate the size of a dynamic array
    created using a dereference declaration like int *numbers and
    allocating via malloc or calloc: numbers=(int
    *)malloc(sizeof (int)*10);

    using sizeof(numbers) will return the pointers size...

    is there a possibility?

    D@nny
    --
    life already is expensive, so why waste money on expensive
    software.
  • Mike Wahler

    #2
    Re: sizeof dynamic array

    "D@nny" <no@thanx.nl> wrote in message
    news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...[color=blue]
    > hi,
    >
    > i would like to know how to calculate the size of a dynamic array[/color]

    Determine how big you need it to be, and allocate that much.
    [color=blue]
    > created using a dereference declaration like int *numbers[/color]

    That's not a 'dereference declaration'. Its a declaration
    of a pointer object.
    [color=blue]
    >and
    > allocating via malloc or calloc: numbers=(int
    > *)malloc(sizeof (int)*10);[/color]

    Never cast the return value from 'malloc()'. See the FAQ
    for details.
    [color=blue]
    >
    > using sizeof(numbers) will return the pointers size...[/color]

    Yes. Because 'numbers' is a pointer.
    [color=blue]
    >
    > is there a possibility?[/color]

    Yes. You know the size when you allocate it. Just retain
    that value (i.e. store it in a 'size_t' object).

    int *numbers = 0;
    size_t sz = 10 * sizeof *numbers;

    if(numbers = malloc(sz))
    {
    printf("%lu bytes allocated.\n", (unsigned long)sz);
    /* do stuff */
    free(numbers);
    }

    -Mike


    Comment

    • Martin Ambuhl

      #3
      Re: sizeof dynamic array

      D@nny wrote:[color=blue]
      > hi,
      >
      > i would like to know how to calculate the size of a dynamic array
      > created using a dereference declaration like int *numbers and
      > allocating via malloc or calloc:[/color]
      [color=blue]
      >numbers=(int *)malloc(sizeof (int)*10);[/color]

      Guess what: the size of the array is sizeof(int)*10. What did you think
      it was.

      BTW, your code line above is not, at least here, idiomatic. Had you
      lurked before posting (expected usenet behavior) or checked the FAQ
      before posting (expected usenet behavior), you would have no this.

      You have no idea how many people everyday violate those two standard
      rules every day just to post code that casts the return value from
      malloc (corrected several times a day here), uses hard-coded magic
      numbers, uses hard-coded data types in allocation statements, asks
      questions answered multiple times a week (as is yours), and fails to
      include a compilable example.

      #include <stdlib.h>
      int main(void)
      {
      const number_elements = 10;
      int *numbers;
      numbers = malloc(number_e lements * sizeof *numbers);
      if (!numbers) { /* handle error */ }
      else free(numbers);
      return 0;
      }
      [color=blue]
      > using sizeof(numbers) will return the pointers size...
      >
      > is there a possibility?[/color]

      Obviously, there is. If you can figure out how much space to ask malloc
      for, you already know the answer.

      Comment

      • Joona I Palaste

        #4
        Re: sizeof dynamic array

        D@nny <no@thanx.nl> scribbled the following:[color=blue]
        > hi,[/color]
        [color=blue]
        > i would like to know how to calculate the size of a dynamic array
        > created using a dereference declaration like int *numbers and
        > allocating via malloc or calloc: numbers=(int
        > *)malloc(sizeof (int)*10);[/color]
        [color=blue]
        > using sizeof(numbers) will return the pointers size...[/color]
        [color=blue]
        > is there a possibility?[/color]

        Not in standard C. You'll have to use implementation-specific tricks.
        But since you know the size when you allocate the memory, why not simply
        keep track of it?

        --
        /-- Joona Palaste (palaste@cc.hel sinki.fi) ------------- Finland --------\
        \-------------------------------------------------------- rules! --------/
        "To know me IS to love me."
        - JIPsoft

        Comment

        • Al Bowers

          #5
          Re: sizeof dynamic array



          D@nny wrote:[color=blue]
          > hi,
          >
          > i would like to know how to calculate the size of a dynamic array
          > created using a dereference declaration like int *numbers and
          > allocating via malloc or calloc: numbers=(int
          > *)malloc(sizeof (int)*10);
          >
          > using sizeof(numbers) will return the pointers size...
          >
          > is there a possibility?[/color]

          What you should do is declare a variable, ex. size_t nelements,
          that you can use to store the number of elements allocated for
          the int array. If you dynamically allocated the array for
          10 elements, then store in nelements the value 10. If you
          modify the number of array elements, then modify nelements
          appropriately. In the occasion where you might need the
          total size of the allocation, just multiply the sizeof(int)
          with nelements.

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

          int main(void)
          {
          int *iarr, *tmp;
          size_t nelements = 0;

          iarr = malloc((sizeof *iarr)*10);
          if(iarr) nelements = 10;
          printf("Number of elements allocated is %u\n"
          "Size of the allocation is %u\n\n",
          nelements, nelements*sizeo f(int));
          if(nelements)
          {
          puts("An attempt to increase the allocation one element\n");
          tmp = realloc(iarr,(s izeof *iarr)*(nelemen ts+1));
          if(tmp)
          {
          iarr = tmp;
          nelements++;
          }
          printf("Number of elements allocated is %u\n"
          "Size of the allocation is %u\n\n",
          nelements, nelements*sizeo f(int));
          }
          free(iarr);
          return 0;
          }


          --
          Al Bowers
          Tampa, Fl USA
          mailto: xabowers@myrapi dsys.com (remove the x to send email)
          Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


          Comment

          • Skybuck Flying

            #6
            Re: sizeof dynamic array


            "Mike Wahler" <mkwahler@mkwah ler.net> wrote in message
            news:cfmjd.7863 $O11.7228@newsr ead3.news.pas.e arthlink.net...[color=blue]
            > "D@nny" <no@thanx.nl> wrote in message
            > news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...[color=green]
            > > hi,
            > >
            > > i would like to know how to calculate the size of a dynamic array[/color]
            >
            > Determine how big you need it to be, and allocate that much.
            >[color=green]
            > > created using a dereference declaration like int *numbers[/color]
            >
            > That's not a 'dereference declaration'. Its a declaration
            > of a pointer object.
            >[color=green]
            > >and
            > > allocating via malloc or calloc: numbers=(int
            > > *)malloc(sizeof (int)*10);[/color]
            >
            > Never cast the return value from 'malloc()'. See the FAQ
            > for details.[/color]

            Hello I am not the original poster... but this seems interesting.

            I can't the answer in this FAQ;



            Why shouldn't it be typecasted ?

            1. Maybe because it doesn't compile on true c compilers ?

            2. Or does it lead to bugs ?

            Bye,
            Skybuck.


            Comment

            • Barry Schwarz

              #7
              Re: sizeof dynamic array

              On Sun, 7 Nov 2004 15:47:26 +0100, "Skybuck Flying"
              <nospam@hotmail .com> wrote:
              [color=blue]
              >
              >"Mike Wahler" <mkwahler@mkwah ler.net> wrote in message
              >news:cfmjd.786 3$O11.7228@news read3.news.pas. earthlink.net.. .[/color]

              snip
              [color=blue][color=green]
              >> Never cast the return value from 'malloc()'. See the FAQ
              >> for details.[/color]
              >
              >Hello I am not the original poster... but this seems interesting.
              >
              >I can't the answer in this FAQ;
              >
              >http://www.eskimo.com/~scs/C-faq/s7.html
              >
              >Why shouldn't it be typecasted ?[/color]

              a. It is unnecessary in C. Superfluous casts should always be
              avoided.

              b. It leads to undefined behavior (under C89, currently the standard
              implemented by most popular compilers) if the prototype for malloc is
              omitted.


              <<Remove the del for email>>

              Comment

              • Method Man

                #8
                Re: sizeof dynamic array


                "D@nny" <no@thanx.nl> wrote in message
                news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...[color=blue]
                > hi,
                >
                > i would like to know how to calculate the size of a dynamic array
                > created using a dereference declaration like int *numbers and
                > allocating via malloc or calloc: numbers=(int
                > *)malloc(sizeof (int)*10);
                >
                > using sizeof(numbers) will return the pointers size...
                >
                > is there a possibility?
                >[/color]

                As others have mentioned, keep track of the size when you allocate the
                array.

                I suppose one possible exception is a null-terminated char array where you
                can call 'strlen' to get the length of the array.


                Comment

                • Default User

                  #9
                  Re: sizeof dynamic array


                  Method Man wrote:[color=blue]
                  > "D@nny" <no@thanx.nl> wrote in message
                  > news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...[color=green]
                  > > hi,
                  > >
                  > > i would like to know how to calculate the size of a dynamic array[/color][/color]
                  [color=blue]
                  > As others have mentioned, keep track of the size when you allocate[/color]
                  the[color=blue]
                  > array.
                  >
                  > I suppose one possible exception is a null-terminated char array[/color]
                  where you[color=blue]
                  > can call 'strlen' to get the length of the array.[/color]

                  That gives you length of the string, not the size of the array. They
                  are often different. So for instance, you have no way of knowing
                  whether you can extend the string safely unless you know the size of
                  the underlying array.



                  Brian

                  Comment

                  • Mike Wahler

                    #10
                    Re: sizeof dynamic array


                    "Method Man" <a@b.c> wrote in message
                    news:H1Ljd.5882 $hp3.612532@rea d2.cgocable.net ...[color=blue]
                    >
                    > "D@nny" <no@thanx.nl> wrote in message
                    > news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...[color=green]
                    > > hi,
                    > >
                    > > i would like to know how to calculate the size of a dynamic array
                    > > created using a dereference declaration like int *numbers and
                    > > allocating via malloc or calloc: numbers=(int
                    > > *)malloc(sizeof (int)*10);
                    > >
                    > > using sizeof(numbers) will return the pointers size...
                    > >
                    > > is there a possibility?
                    > >[/color]
                    >
                    > As others have mentioned, keep track of the size when you allocate the
                    > array.
                    >
                    > I suppose one possible exception is a null-terminated char array where you
                    > can call 'strlen' to get the length of the array.[/color]

                    char *array = malloc(100);
                    size_t sz = 0;

                    if(array)
                    {
                    strcpy(array, "Hello");
                    sz = strlen(array); /* sz != 100 */
                    }

                    free(array);

                    -Mike


                    Comment

                    • Method Man

                      #11
                      Re: sizeof dynamic array


                      "Mike Wahler" <mkwahler@mkwah ler.net> wrote in message
                      news:mkUjd.2147 0$KJ6.3693@news read1.news.pas. earthlink.net.. .[color=blue]
                      >
                      > "Method Man" <a@b.c> wrote in message
                      > news:H1Ljd.5882 $hp3.612532@rea d2.cgocable.net ...[color=green]
                      > >
                      > > "D@nny" <no@thanx.nl> wrote in message
                      > > news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...[color=darkred]
                      > > > hi,
                      > > >
                      > > > i would like to know how to calculate the size of a dynamic array
                      > > > created using a dereference declaration like int *numbers and
                      > > > allocating via malloc or calloc: numbers=(int
                      > > > *)malloc(sizeof (int)*10);
                      > > >
                      > > > using sizeof(numbers) will return the pointers size...
                      > > >
                      > > > is there a possibility?
                      > > >[/color]
                      > >
                      > > As others have mentioned, keep track of the size when you allocate the
                      > > array.
                      > >
                      > > I suppose one possible exception is a null-terminated char array where[/color][/color]
                      you[color=blue][color=green]
                      > > can call 'strlen' to get the length of the array.[/color]
                      >
                      > char *array = malloc(100);
                      > size_t sz = 0;
                      >
                      > if(array)
                      > {
                      > strcpy(array, "Hello");
                      > sz = strlen(array); /* sz != 100 */
                      > }
                      >
                      > free(array);
                      >[/color]

                      Yeah, I should have noted that 'strlen' gives the length of the string and
                      not necessarily the allocated size of the array. That's why I said "possible
                      exception".


                      Comment

                      • Mike Wahler

                        #12
                        Re: sizeof dynamic array


                        "Method Man" <a@b.c> wrote in message
                        news:cwVjd.5957 $hp3.640238@rea d2.cgocable.net ...[color=blue]
                        >
                        > "Mike Wahler" <mkwahler@mkwah ler.net> wrote in message
                        > news:mkUjd.2147 0$KJ6.3693@news read1.news.pas. earthlink.net.. .[color=green]
                        > >
                        > > "Method Man" <a@b.c> wrote in message
                        > > news:H1Ljd.5882 $hp3.612532@rea d2.cgocable.net ...[color=darkred]
                        > > >
                        > > > "D@nny" <no@thanx.nl> wrote in message
                        > > > news:fZljd.1744 $jf.1230@amsnew s03-serv.chello.com ...
                        > > > > hi,
                        > > > >
                        > > > > i would like to know how to calculate the size of a dynamic array
                        > > > > created using a dereference declaration like int *numbers and
                        > > > > allocating via malloc or calloc: numbers=(int
                        > > > > *)malloc(sizeof (int)*10);
                        > > > >
                        > > > > using sizeof(numbers) will return the pointers size...
                        > > > >
                        > > > > is there a possibility?
                        > > > >
                        > > >
                        > > > As others have mentioned, keep track of the size when you allocate the
                        > > > array.
                        > > >
                        > > > I suppose one possible exception is a null-terminated char array where[/color][/color]
                        > you[color=green][color=darkred]
                        > > > can call 'strlen' to get the length of the array.[/color]
                        > >
                        > > char *array = malloc(100);
                        > > size_t sz = 0;
                        > >
                        > > if(array)
                        > > {
                        > > strcpy(array, "Hello");
                        > > sz = strlen(array); /* sz != 100 */
                        > > }
                        > >
                        > > free(array);
                        > >[/color]
                        >
                        > Yeah, I should have noted that 'strlen' gives the length of the string and
                        > not necessarily the allocated size of the array.[/color]

                        Right. The point is that there is no way to determine after the fact
                        how much memory was allocated. Another 'subtle' point: 'malloc()'
                        is required to attempt to allocate *at least* the requested size.
                        It is allowed to (and often does) allocate more (but the program
                        must only access within bounds of the requested size).
                        [color=blue]
                        > That's why I said "possible
                        > exception".[/color]

                        In standard C, no exceptions.

                        -Mike


                        Comment

                        Working...