void * to C *中的struct *

时间:2014-03-03 17:56:56

标签: c pointers struct void-pointers

我有一个基本的类型转换问题......我有一个结构

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;

我做错了什么?

非常感谢你的帮助:) 维克。

2 个答案:

答案 0 :(得分: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 :(得分: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;
}