I am attempting to copy a character from an array to a character pointer by means of a function. Following is my code:
#include<stdio.h>
void pass(void* arg){
char arr[1];
arr[0]='X';
memcpy((char *)arg,arr,1);
}
void main(){
char *buf=malloc(sizeof(char));
pass(buf);
printf("%c",buf);
free(buf);
}
Here, the pointer buf prints a garbage value. I tried the reverse of the above program as follows:
#include<stdio.h>
void pass(void* arg){
char arr[1];
memcpy(arr,(char *)arg,1);
printf("%c",arr[0]);
}
void main(){
char *buf=malloc(sizeof(char));
buf[0]='X';
pass(buf);
free(buf);
}
This was successful and arr[0] prints the value as X. Could someone clarify why does the first case fail?