0

我读过一本书,其中指定了这一点:

//: C03:SimpleCast.cpp
int main() {
int b = 200;
unsigned long a = (unsigned long int)b;
} ///:~

“强制转换很强大,但它可能会让人头疼,因为在某些情况下它会迫使编译器将数据视为(例如)比实际更大的数据,因此它将占用更多的内存空间;这可能会践踏其他数据. 这通常发生在转换指针时,而不是像上面显示的那样进行简单转换时。”

现在你能提供一个铸造指针可以践踏其他数据的例子吗?

4

4 回答 4

5
int main(void)
{
    short int a = 5;
    short int b = 7;
    *(long int*)&a = 0;
}

假设sizeof(long) > sizeof(short),并假设编译器a之前放入堆栈bb将被丢弃。

于 2010-06-02T18:57:18.020 回答
1
int main() { 
    char a[] = "This is a string.";

    *(long *)a = 12345678;  // will typically overwrite first four or eight bytes of a.

    std::cout << a;
    return 0;
}
于 2010-06-02T18:58:39.330 回答
0
char unix[5]="unix";
char* first= &(unix[0]);
int * intptr= (int*) first;
*first=64;
printf("%s\n",unix); /* prints @ /*
于 2010-06-02T18:59:27.830 回答
0

由于这被标记为 C++,而不是 C,我还建议阅读 C++ 样式转换而不是 C 样式转换:

static_cast<Derived *>(pBase)->DMethod();
if (dynamic_cast<Derived *>(pBase)) dynamic_cast<Derived *>(pBase)->DMethod();
const_cast<CRect &>(constRect).x = 3;
int *pInt = reinterpret_cast<int *>(charbuff);

我强烈推荐 Scott Myer 的书 Effective C++, 55 Specific Ways to Improvement Your Programs and Designs, 3rd Edition,它很好地解释了这些。确保您获得了第 3 版,尽管第 2 版也可能包含 C++ 样式转换。

基本上,如果您使用 C++ 并且您的编译器是在过去 10 年内编写的,则永远不要使用 C 风格的强制转换。使用 C++ 样式转换。

于 2010-06-03T01:33:01.403 回答