-1

Is it a right way to pass a pointer to dynamic array? Is it going to work? If not, explain why, if it does, explain why as well. Thank you.

struct record
{
    char * community_name;
    double data[10];
    double crimes_per_pop;
};

void allocate_struct_array(struct record *** r);

int main()
{
    /* allocating pointer to an array of pointers */
    struct record ** r;

    /* passing its address to a function */
    allocate_struct_array( &(**r) );
}

/* function gets an address */
void allocate_struct_array(struct record *** r)
{
   ...
}

What I was trying to do is to allocate an array of pointers, where each pointer points to structure record. Function suppose to allocate this array using just pointer to r, which was declared in main. Was playing with this code, but cannot make it to work.

7
  • 1
    I have no idea what the code snippet has to do with the question. I don't really have any idea what the question means, either. Commented Dec 11, 2011 at 2:28
  • to @AndrewMarshall: yes, I tried it. Commented Dec 11, 2011 at 7:29
  • to @OliCharlesworth: question is ease - how to make it work? without changind struct record ** r to struct record * r? Commented Dec 11, 2011 at 7:30
  • You surely do not need a triple pointer unless you're dealing with 2d arrays. Commented Dec 11, 2011 at 7:32
  • @moshbear: you mean 3d arrays :) Commented Dec 11, 2011 at 7:37

2 Answers 2

2

I don't know what you are trying to do, but at least you have a programmatic error.

allocate_struct_array( &(**r) );

needs to be -

allocate_struct_array(&r);
Sign up to request clarification or add additional context in comments.

Comments

1

In the function interface, you only need a double pointer struct record **r and not a triple pointer.

An array can be represented by a struct record *array; so a pointer to that is struct record **ptr_to_array.

You call the function with &array.

struct record
{
    char * community_name;
    double data[10];
    double crimes_per_pop;
};

void allocate_struct_array(struct record **r);

int main()
{
    struct record *r;
    allocate_struct_array(&r);
}


void allocate_struct_array(struct record **r)
{
    *r = malloc(23 * sizeof(struct record));
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.