How to determine the size of dynamical arrays?

Discussion in 'C Programming' started by FraterQ, Jul 2, 2003.

  1. FraterQ

    FraterQ Guest

    FraterQ, Jul 2, 2003
    #1
    1. Advertisements

  2. FraterQ

    Tom St Denis Guest

    "dynamical" ???

    This question is asked far too often. Go read the FAQ.

    Tom
     
    Tom St Denis, Jul 2, 2003
    #2
    1. Advertisements

  3. FraterQ wrote:

    When you allocate the memory, you know how much you're allocating.

    Don't Forget.
     
    Richard Heathfield, Jul 2, 2003
    #3
  4. Ask the one who has allocated the memory block to keep the size in some
    memory. A common tip is the following :

    typedef struct
    {
    int *a; /* dynamic array of int */
    size_t n;
    }
    buf_s;

    buf_s buf;

    buf_create (&buf, 123);

    with

    int buf_create (buf_s * this, size_t n)
    {
    err = 1;

    if (this)
    {
    this->a = NULL;
    this->n = 0;

    {
    int *p = malloc (sizeof *p * n); /* <stdlib.h> */

    if (p)
    {
    this->a = p;
    this->n = n;
    err = 0;
    }
    }
    }
    return err;
    }
     
    Emmanuel Delahaye, Jul 3, 2003
    #4
  5. (FraterQ) wrote (02 Jul 2003) in
    / comp.lang.c:
    Remember it, for goodness' sake! You can't dynamically create
    without having the size information; why do you throw away what you
    already know?
     
    Martin Ambuhl, Jul 3, 2003
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.