memset Implementation

Hi everyone, I was thinking of implementing memset.... but got stuct ... Here is the code that I wrote ...

#include<stdio.h>
void my_memset(void *ptr,int x,int no_of_bytes){

unsigned char c;

while(no_of_bytes--){
c = (unsigned char) x;

*((char *)ptr ) = c ;

((char *))ptr++;

}

}
int main(){

int *array,i;
array = (int *)malloc(10*sizeof(int));

my_memset(array,0,40);

for(i=0;i<10;i++){
printf("%d ",array[i]);
}
return 0;

}

This wont work when we want to initialize the array by 1. The problem is we are initializing each byte with 1. But other than this how to make this function generic and type cast the void pointer accordingly ?
You can't. Passing void * means giving up any chance of ever finding out what was really passed in. That's why it's only used when knowing what was passed in is not necessary, such as when passing raw buffers, or when writing C-style containers.

By the way, memset() is typically implemented in Assembly and takes advantage of register sizes to set more than one byte at once.
Topic archived. No new replies allowed.