是否可以永久重铸变量,或者有一个包装函数,使变量的行为与其他类型相同?
我想要实现我在其他问题中发布的内容: Typecasting variable with another typedef
更新:已将GCC添加为编译器。可以有一个有用的扩展吗?
答案 0 :(得分:3)
是的,您可以将变量从一种类型转换为另一种类型:
int x = 5;
double y = (double) x; // <== this is what a cast looks like
但是,如果您要求,则无法就地修改标识符“x”的类型。尽管如此,您可以引入另一个范围,并使用某种新类型重新声明该标识符:
int x = 5;
double y = (double) x;
{
double x = y; // NOTE: this isn't the same as the 'x' identifier above
// ...
}
// NOTE: the symbol 'x' reverts to its previous meaning here.
你可以做的另一件事,虽然它真的是一个可怕的,可怕的想法是:
int x = 5;
double new_version_of_x = (double) x; // Let's make 'x' mean this
#define x new_version_of_x
// The line above is pure evil, don't actually do it, but yes,
// all lines after this one will think 'x' has type double instead
// of int, because the text 'x' has been rewritten to refer to
// 'new_version_of_x'. This will likely lead to all sorts of havoc
答案 1 :(得分:1)
通过投射然后分配来实现这一点。
int f(void * p) {
int * i;
i = (int *)p;
//lots of code here with the i pointer, and every line
//really thinks that it is an int pointer and will treat it as such
}
编辑从您链接的其他问题:
typedef struct {
unsigned char a;
unsigned char b;
unsigned char c;
} type_a;
typedef struct {
unsigned char e;
unsigned char f[2];
} type_b;
//initialize type a
type_a sample;
sample.a = 1;
sample.b = 2;
sample.c = 3;
现在sample
已初始化,但您希望以不同方式访问,您希望假装实际上该变量具有其他类型,因此您声明指向您要“伪装”sample
的类型的指针:
type_b * not_really_b;
not_really_b = (type_b*)&sample;
看,这就是整个魔术。
not_really_b->e
等于1
not_really_b->f[0]
等于2
not_really_b->f[1]
等于3
这会回答你的问题吗?
答案 2 :(得分:0)
其他答案更好(声明您想要的类型的变量,然后进行分配)。如果这不是您要求的,您可以使用宏:
long i;
#define i_as_int ((int)i)
printf( "i = %ld\n", i);
printf( "i = %d\n", i_as_int);
但如果这就是你的意思,那么说(int) i
会不会更清楚?
答案 3 :(得分:-1)
As long as you realize in C pointers are nothing but addresses of memory
locations of certain types, you should have your answer. For example the
following program will print the name of the file
int main(int argc, char *argv[]) {
int *i;
i = (int *) argv[0];
printf("%s\n", argv[0]);
printf("%s\n", ((char *) i));
}