2014-03-03 51 views
0

我有一个基本的类型转换问题...我有一个结构无效*为结构*用C

typedef struct teststruct { 
    int a; 
} test; 

和简单的功能

void testfunc(void **s) 
{ 
    printf("trying malloc\n"); 
    s[0] = (test*)s[0]; 
    s[0] = (test*)malloc(sizeof(test)); 
    s[0]->a = 2; 
} 

然而,当我编译,我得到

test.c:21:7: error: member reference base type 'void' is not a structure or union 
    s[0]->a = 2; 

我在做什么错?

非常感谢您的帮助:) Vik。

+0

为什么参数'无效**'和'不**测试'? – Nabla

+0

我需要从javascript中的nodejs的外部函数接口调用方法。它理解无效而不是自定义的结构。 –

+1

请勿施放'malloc'的结果。 – Barmar

回答

3

线是没有意义:

s[0] = (test*)s[0]; 

作为其分配s[0]到自身。

我怀疑你认为它改变了s[0]void*test*类型。
但这并不准确。

类型转换只影响在类型转换时立即解释变量的方式。
它不会在任何持久的意义上改变变量的类型。

其结果是,当你的程序达到这条线:

s[0]->a = 2; 

s[0]仍然是一个void*,所以去引用它的变量a无效。

你真正想要的是:

((test*)s[0])->a = 2; 
1

那是因为你不能在你的范围内改变一个变量的类型。你必须用新的类型定义一个新的。

void testfunc(void **s) 
{ 
    printf("trying malloc\n"); 
    test * s_test_type = s[0]; // no need to cast to/from void * 
    s_test_type = (test*)s[0]; 
    s_test_type = (test*)malloc(sizeof(test)); 
    s_test_type->a = 2; 
}