Search code examples
carrayspointersmemset

Using memset with pointer to an array


How do I memset an array using a pointer to that array?

int *A, n;

printf("\n Enter the size of array : ");
scanf("%d",&n);

A = (int*) malloc(sizeof(*A) * n);

int i = 0;

memset(*A,5,n * sizeof(*A));

for(i = 0; i < n; i++)
    printf("%d ", A[i]);

Solution

  • The compiler doesn't emit warnings for no reason:

    warning: passing argument 1 of 'memset' makes pointer from integer without a cast
    expected 'void *' but argument is of type 'int'
    

    This means that you are not passing the right type to the first argument of memset(), which indeed wants a pointer, while you are passing an integer.

    Your pointer A is fine as is, dereferencing it (*A) is not needed and is wrong, the correct call is:

    memset(A, 5, n * sizeof(*A));
    

    More importantly though, this is not what you want to do! If you think the above sets all the elements of the allocated array to 5 that's not the case. Instead, memset() sets every single byte to 5 (see the manual page). Since an int is more than one byte (usually 4), this will fill your array with the value 0x05050505 (decimal 84215045) instead of 5.

    In order to set every element to 5 you'll need a for loop:

    int i = 0; 
    for (i = 0; i < n; i++)
        A[i] = 5;
    

    Finally, don't cast the return value of malloc():

    A = malloc(sizeof(*A) * n);