Allocating memory for pointers inside structures in functions

808 Views Asked by At

Let's say I declare a structure as it follows:

typedef struct {
    int *numbers;
    int size; // Size of numbers once treated as array
} sstruct;

And I create in main() a pointer to structure (in order to later pass it by reference) using sstruct *example;.

Then I have a function, call it allocpositions(), in which I pretend to allocate memory positions for the *p pointer contained in *example.

If I would want to allocate positions to *example, it would be enought to pass the direction &example to the function, that would receive it as **a and then do something like a = (sstruct **)malloc(N*sizeof(sstruct *)), but I don't see how I can allocate directly to *p inside the function.

And once allocated, would I still be able to refer the elements in *p as example->p[index] inside allocpositions()?

I'd appreciate any help!

edit

Example code illustrating what I try to achieve:

typedef struct {
    int *numbers;
    int size; // size of numbers once treated as array
} ssm;

main() {
    ssm *hello;
    f_alloc(&hello);
}

void f_alloc(ssm **a) {
    // Here I want to allocate memory for hello->p
    // Then I need to access the positions of hello->p that I just allocated
}
1

There are 1 best solutions below

16
On BEST ANSWER

Code with comments:

void f_alloc(ssm **a) {

    *a = malloc(sizeof(ssm)); // Need to allocate the structure and place in into the *a - i.e. hello in main
    (*a)->p = malloc(sizeof(int)); // Allocate memory for the integer pointer p (i.e. hello ->p;
}

EDIT

I think this is what you are requiring:

void f_alloc(ssm **a, unsigned int length) {

    *a = malloc(sizeof(ssm)); // Need to allocate the structure and place in into the *a - i.e. hello in main
    (*a)->p = malloc(sizeof(int) * length); // Allocate memory for the integer pointer p (i.e. hello ->p;
    (*a)->v = length; // I am assuming that this should store the length - use better variable names !!!
}

Then a function to set/get

bool Set(ssm *s, unsigned int index, int value) {
   if (index >= s->v) {
       return false;
   }
   s->p[index] = value;
   return true;
}

bool Get(ssm *s, unsigned int index, int *value) {
   if (index >= s->v) {
       return false;
   }
   *value = s->p[index];
   return true;
}

I leave doing the free bit to the reader.

EDIT 2

As I am in a good mood.

void Resize(ssm**a, unsigned int new_length)
{
   (*a)->p = relloc((*a)->p, sizeof(int) * new_size);
   (*a)->v = new_length;
}
void Free(ssm *a)
{
   free(a->p);
   free(a);
}

you can make it more fault tolerant to check that malloc/realloc have worked