Reputation: 3
How would I do this, as I dont know if I can read a void
pointer so I want to convert it to a string first. Here is my attempt while testing it:
void* test1;
char test2[] = "ha 21";
char test3[50];
test1 = test2;
test3 = test1;
printf("%s", test3);
return 0;
When I try to make test1 = test 2
is probably wrong as well but that is just to show what should be in the void
pointer. I am only trying to see how I can convert a void pointer containing a string to a string.
Upvotes: 0
Views: 3634
Reputation: 12634
When I try to make test1 = test2 is probably wrong as well but that is just to show what should be in the void pointer.
test1 = test2
is perfectly right. From C Standard#6.3.2.3p1
1 A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
The problem is with this statement:
test3 = test1;
test3
is an array and you cannot assign test1
to test3
because, in C, array names are non modifiable lvalues.
Instead, you should copy the contents of test1
to test3
and you can use strcpy()
for this.
But strcpy()
is not safe because it has no way of knowing how large the destination buffer is and you may end up with buffer overflow if the destination buffer is not long enough to hold the source string (including null terminating character). Before copying string if you can ensure that the destination buffer is long enough to hold source string (including null terminating character) than its perfectly fine to use strcpy()
to copy source string to destination buffer. In your case since the destination buffer size is 50
which is long enough to hold the source string "ha 21"
you can safely use the strcpy()
. So, instead of this:
test3 = test1;
You should do:
strcpy(test3, test1);
Additional:
The strncpy()
is not a safer version of strcpy()
.
Read here about why strncpy()
is introduced?
However, you can use strncpy()
as an alternative (which most of the developers do) because it can prevents from buffer overflow but remember no null-character is implicitly appended at the end of destination if source is longer than the maximum number of characters to be copied from source. You need to take care of this scenario explicitly where the source is longer than destination.
Upvotes: 0
Reputation: 2813
Since test3
is an array type it can not be assigned.
In C you can convert every pointer to void *
and back (it is casted implicitly).
So a possible solution is to declare test3
as pointer:
void *test1;
char test2[] = "ha 21";
char *test3;
test1 = test2;
test3 = test1;
printf("%s", test3);
Or if you want to copy the memory (as mentioned in comments):
void *test1;
char test2[] = "ha 21";
char test3[50];
test1 = test2;
strcpy(test3, test1);
printf("%s", test3);
Upvotes: 1