Memsetting pointer to an array

121 views Asked by At

I have a pointer to an array. I know how many number of items that array can hold but the length of each item is dynamic. So how to memset() the array in this case.

Int8 *data[4]; //array can hold maximum of 4 elements

Also I want to allocate memory for each item. How to do this?

3

There are 3 answers

3
Sourav Ghosh On

First, you initialize the array at definition time by saying,

Int8 *data[4] = { NULL };  //NULLify all the elements.

Then, you need to use a loop to allocate memory to each element of the array, like

for (index = 0; index < 4; index++)
    data[index] = calloc(SIZE, sizeof(Int8)); //SIZE is a MACRO

FWIW, calloc() will returned "zero"ed memory (if success), so no need to memset() separately if you want the memory to be initialized to 0.

Obviously, you need to check for the success of the allocation.

1
Mike Armstrong On

First I would sizeof the individual elements. Use a for loop and recurs the number of elements within your declaration.

Set the sizeof return equal to an integer so that you can access it, then memset with that integer for each element.

Int8 *somedata;

for (int i = 0; i < 4; i++) {    // for i less than 4 do increment i
    memset(data[i], somedata, sizeof(data[i]));   // memset data at point i, with value somedata, which has a size data[i] 
}

Hope that gives you something to go on!

0
rabi shaw On
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main ( void )
{
        int *pointer_array[4],i=0;

/* Allocating memory and storing the address in pointer_array[] */
        for ( i=0; i<4; i++ )
        {
                pointer_array[i] = malloc ( sizeof(int) );
        }

/* Memset the values with 0 */
        for ( i=0 ;i<4; i++ )
        {
                memset( pointer_array[i], 0 , sizeof(int) );
        }
/*printing the values */
        for ( i=0 ;i<4; i++ )
        {
                printf ( "\n %d", *pointer_array[i] );
        }
/* deallocating the memory */
        for (i=0; i<4; i++ )
        {
                free ( pointer_array[i] );
        }

        return ( 0 );

}

output:
rabi@rabi-VirtualBox:~/rabi/c$ ./a.out 

 0
 0
 0
 0rabi@rabi-VirtualBox:~/rabi/c$