0

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?

1
  • 1
    Turn your warnings knob up a notch. Commented Dec 13, 2015 at 9:54

2 Answers 2

3

You have to print *buf or buf[0] instead of buf to print the first element of the array pointed by buf.

Also note that passing data having type char* to be printed via %c in printf(), which expect data having type int, is undefined behavior due to type mismatch.

Try this:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void pass(void* arg){
  char arr[1];
  arr[0]='X';
  memcpy((char *)arg,arr,1);
}
int main(void){
  char *buf=malloc(sizeof(char));
  pass(buf);
  printf("%c",buf[0]);
  free(buf);
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

3

Your problem lies here:

char *buf=malloc(sizeof(char));
:
printf("%c",buf);

because buf is a pointer to a character, not a character. The character is *buf, or buf[0] so you can fix it with:

printf ("%c", *buf);

As an aside, it's totally unnecessary to create arr and call memcpy in the first example when you can simply do:

void pass (void* arg) {
    ((char*)arg)[0] = 'X';
}

Dynamic memory allocation for a character in this case is also unnecessary when you can just replace the malloc line with a simple:

char buf[1];

(and get rid of the free line, of course).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.