这个例子是由示范,但我需要转换指针作为例子如何将指针转换为嵌套在结构中的void?
我收到以下错误:
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
的代码是这样的:
#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;
}
代码的注释部分运行良好。我明白,处理器不能取消引用没有额外变量的指针,编译器将创建一个额外的变量,但我想了解如何投射嵌套在结构中的指针而不创建额外的变量?
为了使代码看起来更加紧凑,我会经常使用类似的东西,并且我想将它写入一行而不用额外的变量。
'的strcpy(((结构测试2 *)P- > ptr) - > astr,“hello world”);' – BLUEPIXY 2014-12-01 18:31:24
我需要像这样转换:'p - >(struct test2 *)ptr-> astr'但是编译器得到错误 – 2014-12-01 18:31:59
代码需要测试从malloc返回的值在使用之前。否则代码将取消引用地址0,这将导致seg故障事件 – user3629249 2014-12-01 18:34:08