Amir reza Riahi
Amir reza Riahi

Reputation: 2450

Why does memset receive the second argument as an integer?

The man page of memset function in C, says

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

And the signature of memset is as below:

void *memset(void *s, int c, size_t n);

Since the function fills the first n bytes of the memory, why the c's type is int and not char? Couldn't it be char and works just fine? What will happen if we set c a number greater than size of a byte?

I tried to play with memset to get more into it but it didn't help me.

#include <string.h>
#include <stdio.h>

int
main(int argc, char *argv[]) {

        char* s[5] = {0, 0, 0, 0, 0};
        memset((void*)s, 257, 5);
        for (int i=0; i<5; i++)
                fprintf(stdout, " %d", s[i]);
        putc('\n', stdout);
        return 0;
}

The output is:

[amirreza@localhost memst]$ gcc memst.c 
[amirreza@localhost memst]$ ./a.out 
 16843009 0 0 0 0

Upvotes: 2

Views: 111

Answers (0)

Related Questions