2016-04-13 141 views
1

所以基本上我希望能够继续沿着这条(C++)铸造INT为char指针(INT是在INT形式字符)

char *test1 = "hey"; 
int test2 = (int)test1; 
char *test3 = (char*) &test2; 
printf("%s", test3); 
// have the output as hey 

做一些这甚至可能吗?我知道这不能正常工作,但我只想知道是否有工作方法。是的,我想使用字符指针和整型,所以,不,我不想用字符串

+0

[C++:它是安全投指针为int,后来回再次指针?](http://stackoverflow.com/questions/3567905/c-is-it-安全地转换为指针到int和稍后返回指针) –

+1

请注意'char * test1 =“hey”;'不应该编译。一些编译器有一个允许这样做的扩展,但是你应该使用'char test1 [] =“hey”;'或'const char * test1 =“hey”;'或者更好一点'std :: string test =“hey”;' – NathanOliver

+1

**甚至有可能吗?你已经写了一些代码来做一些可能或不可行的事情。你试图完成什么? –

回答

2
char *test1 = "hey"; 
int test2 = (int)test1; 
char *test3 = (char*) test2; // Note that the ampersand has been removed 
printf("%s", test3); 

可能会奏效,如果int和指针大小相同(他们往往是,但它不能保证)。

但是,当您指定test3时,您将采用test2的地址,而不是其值,这正是我认为您的确应该做的。

+0

指针通常是_unsigned_整数。 –

+0

非常感谢! –

+0

如果您想给用户名誉,请检查答案为“已接受”;) –

1

该代码表示​​未定义的行为,因此不正确。

然而,有一种方法可以合法地做你想做的事情。看评论内嵌的解释:

#include <cstddef> 
#include <cstdint> 
#include <cstdio> 

int main() 
{ 
    // string literals are const 
    const char *test1 = "hey"; 

    // intptr_t is the only int guaranteed to be able to hold a pointer 
    std::intptr_t test2 = std::intptr_t(test1); 

    // it must be cast back to exactly what it was 
    const char *test3 = reinterpret_cast<const char*>(test2); 

    // only then will the programs behaviour be well defined 
    printf("%s", test3); 
}