Reputation: 948
This example is made up for demonstration, but I need to cast the pointer as in the example
I am getting the following errors:
test2.c: In function ‘main’:
test2.c:25:12: error: expected identifier before ‘(’ token
test2.c:25:12: error: too few arguments to function ‘strcpy’
test2.c:26:20: error: expected identifier before ‘(’ token
The code is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test {
void *ptr;
char str[300];
};
struct test2 {
int i;
char astr[200];
};
int main(void)
{
struct test *p;
p = malloc(sizeof(struct test));
p->ptr = malloc(sizeof(struct test2));
/*
void *p2;
p2 = p->ptr;
strcpy(((struct test2 *)p2)->astr, "hello world");
printf("%s\n", ((struct test2 *)p2)->astr);
*/
strcpy(p->(struct test2 *)ptr->astr, "hello world");
printf("%s\n", p->(struct test2 *)ptr->astr);
return 0;
}
The commented-out part of the code works well. I understand that the processor can not dereference the pointer without additional variable and the compiler will create an additional variable, but I want to understand how to cast the pointer that is nested in the structure without creating an additional variable?
Just to make the code look more compact, I will often use a similar thing and I'd like to write it in one line without additional variables.
Upvotes: 2
Views: 669
Reputation: 171117
You need to apply ->
to the result of the cast (notice the parentheses around the entire cast expression):
strcpy(((struct test2 *)(p->ptr))->astr, "hello world");
printf("%s\n", ((struct test2 *)(p->ptr))->astr);
Upvotes: 2
Reputation: 5920
C++ variant:
strcpy(reinterpret_cast<struct test2 *>(p->ptr)->astr, "hello world");
Also it is worth pointing out, that strcpy
function is unsafe and should not be used. Use strcpy_s
instead.
Upvotes: 2