0

I am trying to achieve this... A single container which holds an array of structs and inside each of these structs are a single int array which represents an integer like so... 12,345 would be inside an int array[5]={1,2,3,4,5}

What is a way that this could be implemented. My main problem with this implementation is I get lost with all the pointers pointing everywhere and I start having garbage data all over and segfaults all over. Oh yeah by the way everything is dynamic. Well almost everything i guess if you have a struct Container which has a struct inside of that if the container is malloc'd then the struct inside of it is automatically malloc'd also so my guess would be

Container->struct.array

not sure????

1

3 Answers 3

0

you need to write malloc and free function of your struct and contianer yourself and call them everytime when you need a contianer or release its space, for example:

struct outside{
    struct inside *in;
};


struct inside{
    int *array;
};

struct outside *malloc_outside(size_t n) {
    int i;
    struct outside *o;
    o = (struct outside *)malloc(n*sizeof(struct outside));
    for(i=0;i<n;i++) {
        o->in = malloc(sizeof(struct inside));
        o->in->array = NULL;
    }
    return o;
}


void free_outside(struct outside *out) {
    free(out->in->array);
    free(out->in);
    free(out);
    return;
}

and malloc() array's space as how many you need after your malloc_outside()

it's easier to do in C++ by the constructor and destructor .

0
0

I am not sure i've completely understood, but have a look at the following code:

struct MyStruct {
    int *array;
};
struct Container {
    struct MyStruct *array;
};

And the allocation part would be like:

struct Container c;
c.array = malloc(sizeof(struct MyStruct) * NUM_STRUCTS);

for (i = 0; i < NUM_STRUCTS; ++i) {
    c.array[i].array = malloc(get_num_of_digits(12.345) * sizeof(int));    
}

I haven't tested this code, but should do the job :P. Good luck.

0

struct that contains an array of structs that contain a array of integers. no pointers, as u asked

#define SIZE (8)

typedef struct {
    struct data {
        int idata[SIZE];
    };
    struct data arr[SIZE];
}record;

//or
struct data {
    int idata[SIZE];
};

typedef struct data arr[SIZE];

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.