2011-07-05 87 views
-1
typedef struct { 
    unsigned char a, 
    unsigned char b, 
    unsigned char c 
}type_a; 

typedef struct { 
unsigned char e, 
unsigned char f[2] 
}type_b; 

type_a sample; 
sample.a = 1; 
sample.b = 2; 
sample.c = 3; 

铸字变量我如何强制转换并分配如新价值:与其他类型定义

sample = (type_b)sample; // syntax error 
sample.f[1] = 'a'; 
+0

没有理由,如果你的问题已经是“我可以做XXX:”不尝试自己。如果你准备好了这个例子,你为什么不运行它?如果你问“我该怎么做”或“是否合法”,情况会有所不同。 –

+0

也许我应该改变我的问题“可以这样做”。我已经知道这是一个语法错误。对不起,煽动你的bejesus – freonix

+0

这确实是一个区别。一般来说,避免是/否问题在forums + co上不是坏事。 –

回答

1

您不能将一种数据类型转换为另一种不兼容的数据类型。但是,内存是为你打开的。您可以通过以下方式访问它:

typedef struct 
{ 
    unsigned char a; 
    unsigned char b; 
    unsigned char c; 
}type_a; 

typedef struct 
{ 
unsigned char e; 
unsigned char f[2]; 
}type_b; 

type_a sample; 
sample.a = 1; 
sample.b = 2; 
sample.c = 3; 

type_b *sample_b = (type_b *) ((void*) &sample); 

试试自己访问sample_b->esample_b->f看看会发生什么。 value_b = *((value_b*)&value_a)或通过创建这两种类型的工会:

2

你真的应该尝试一下自己。

sample = (type_b)sample; /* Can't cast a structure to 
          another structure. */ 

sample.f[1] = 'a'; /* sample is still of type type_a, 
         and doesn't have an `f` field. */ 
0

号你可以通过转换指针做到这一点。

但是你这样做,要小心。结构可以有不同的数据对齐方式,您可能会得到意想不到的结果

2

否 - C型是静态的,这意味着sample将始终保持type_a类型。然而,你可以实现你想要的使用工会:

union { 
    type_a as_a; 
    type_b as_b; 
} sample; 

sample.as_a.a = 1; 
sample.as_a.b = 2; 
sample.as_a.c = 3; 

sample.as_b.f[1] = 'a'; 

请注意,这不是通常要创建一个对象,是裸union型这样的;通常你会包括structunion,包括标签,让你知道什么类型的对象是在目前的时间:

struct { 
    enum { TYPE_A, TYPE_B } type; 
    union { 
     type_a as_a; 
     type_b as_b; 
    } data; 
} sample; 

/* sample is a TYPE_A right now */ 
sample.type = TYPE_A; 
sample.data.as_a.a = 1; 
sample.data.as_a.b = 2; 
sample.data.as_a.c = 3; 

/* sample is now a TYPE_B */ 
sample.type = TYPE_B; 
sample.data.as_b.f[1] = 'a'; 
0

是的,你可以通过尝试类似的TYPE_A的值复制到TYPE_B

TYPE_B sample_b = *((* TYPE_B)&样品);

的memcpy(& sample_b,&样品,的sizeof(TYPE_A));

铸字只不过是一个类型的表达式转换为另一个。但你似乎想要转换的类型本身,它是固定在编译时(变量声明)

它不清楚背后试图像这样的想法。如果你能更清楚,人们将能够提供更多的见解