arachide
arachide

Reputation: 8066

how to create the array allocated at memory

I used the codes below to create dynamic memory.

unsigned int *mem  ;
mem = (unsigned int*) malloc(mallocSize);

However, I prefer to create an array of pointers. Each pointers will link to one of the memory block.

Upvotes: 0

Views: 143

Answers (4)

Ashutosh
Ashutosh

Reputation: 169

unsigned int **pMemory;
pMemory = (int**)malloc(sizeof(unsigned int *) *number_of_pointers);

for(int index_to_pointer = 0; \
    index_to_pointer < number_of_pointers; \
    index_to_pointer++)

  {  pMemory[index_to_pointer] = (int*)malloc(sizeof(unsigned int));}

I think this is how we allocated dynamic double dimension memory allocation. hope this will help the purpose.

Upvotes: 0

Samy Vilar
Samy Vilar

Reputation: 11130

but I prefer to create an array of pointers each pointer links to one of the memory block above

unsigned int **mem = (unsigned int **)malloc(sizeof(unsigned int *) * number_of_pointers);
// memset(mem, NULL, sizeof(unsigned int *) * number_of_pointers); // recommend it but not needed here, we always set NULL for safety.
for (int index = 0; index < number_of_pointers; index++)
    mem[index] = (unsigned int *)malloc(sizeof(unsigned int) * number_of_ints);

to access individual elements mem[row_index][column_index]

to de-allocate, to reduce or remove memory leaks.

for (int index = 0; index < number_of_pointers; index++)
    free(mem[index]);
free(mem);

rule of thumb, for me anyway, free should be call as often as malloc

Upvotes: 1

Ilmo Euro
Ilmo Euro

Reputation: 5125

Arrays have always compile-time fixed size in C. If that's okay with you, use array syntax:

unsigned int *mem[NUM_PTRS];
for (int i=0; i<NUM_PTRS; i++) {
    mem[i] = malloc(mallocSize);
}

If you need to decide the size at runtime, you need a pointer-to-pointer:

unsigned int **mem;
mem = malloc(sizeof(unsigned int *) * num_ptrs);
for (int i=0; i<num_ptrs; i++) {
    mem[i] = malloc(mallocSize);
}

Upvotes: 0

Jay
Jay

Reputation: 24905

I guess the below code should do it for you. You can create an array of pointers and then store the pointer to each of the memory block in each element of the array. But, the important point is that if you are having an array of unsigned int *, the size passed to malloc must be sizeof(unsigned int). You can modify the below example for other types.

unsigned int *mem[100];

for (i=0; i<100; i++)
{
  mem[i] = malloc(sizeof(unsigned int));
}

Upvotes: 1

Related Questions