void *str_v;
defines str_v
to be of type void *
, i.e., it can store a pointer a variable of any type. However, you need memory space for the characters to be copied by memcpy
from the source to the destination. Therefore, you need to allocate enough memory using malloc
-
char *str_v = malloc(strlen(str) + 1);
strlen
does not count the terminating null byte in the string pointed to by str
. Therefore, you have to allocate one extra byte for the terminating null byte.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
// a string literal is read-only so make str
// const so attempting to change will cause
// compiler error
const char *str = "abcdefghijklmn";
// allocate memory dynamically to the
// string pointed to by str. +1 is for the
// terminating null byte since strlen does
// not count the null byte
char *str_v = malloc(strlen(str) + 1);
// malloc can fail if there is not enough
// memory to allocate. handle it
if(str_v == NULL) {
printf("error in memory allocation\n");
return 1;
}
// copy all bytes in the string pointed to
// by str to the buffer pointed to str_v.
// number of bytes to be copied is strlen(str) + 1
// +1 for copying the terminating byte as well
memcpy(str_v, str, strlen(str) + 1);
// print the copied string. It need not be
// cast to (char *) since str_v is already
// of type (char *)
printf("str_v is %s \n", str_v);
// free the dynamically allocated space
free(str_v);
return 0;
}