Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memset to set array elements to 0

Tags:

c

memset

I'm a newbie playing with memset and pointers.

When I compile and run :

main(){
int a;
int *b = (int *)malloc(5*sizeof(int));
memset(b,0, 5*sizeof(int));
if (b != NULL){
    for(a=0;a<4;a++){
        //b[a] = a*a;
        printf
        ("Value of b %u\n", b[a]);
    }   
}
free(b);
b = NULL;
}

I am able to print all elements value as 0. However when I change the memset line to

memset(b,0, sizeof(b));

I always get one of the elements with a huge number which I assumed to be the address of that element. However on trying to print both address and value at element with:

printf("Value of b %u and address %u\n", b[a], b+(a*sizeof(int)));

I get two long numbers which aren't the same.

What exactly is happening? Have I used memset in the wrong way? Please tell me if I need to attach screenshots of output/ clarify my question.

Thanks!

like image 466
P R Avatar asked Dec 21 '22 00:12

P R


1 Answers

b is a pointer, so sizeof(b) is the size of a pointer, most likely 4 or 8 on current systems. So you're only setting the first few bytes to 0, instead of the entire array.

If you had declared b as an array, e.g.

int b[5];

then sizeof(b) would be the size of the entire array, and your memset would work as you expected.

like image 182
Barmar Avatar answered Dec 24 '22 00:12

Barmar