Ben Eslami
Ben Eslami

Reputation: 94

memcpy and memory location

According to below code:

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

int main(void){
  int i = 10;
  void *byte = calloc(1, 20);
  int j;
  memcpy((char*)byte, &i, sizeof(int));
  memcpy((char*)&j, byte, sizeof(int));
  printf("%d\n", (int)*byte);
  printf("%d\n", j);
  free(byte);
    return 0;
}

The problem is in the line

  printf("%d\n", (int)*byte);

How can I print the content of byte ?

Upvotes: 0

Views: 116

Answers (1)

Hitokiri
Hitokiri

Reputation: 3699

Use:

 printf("%d\n", *(int *)byte);

OR

printf("%c\n", *(char *)byte);

For example, it i = 65, first option will print 65, second option will print A.

int main(void){
  int i = 65;
  void *byte = calloc(1, 20);
  int j;
  memcpy((char*)byte, &i, sizeof(int));
  memcpy((char*)&j, byte, sizeof(int));
  printf("%d\n", *(int *)byte);
  printf("%c\n", *(char *)byte);
  printf("%d\n", j);
  free(byte);
  return 0;
}

The result will be:

65
A
65

Upvotes: 2

Related Questions