C问题:(const void *)vs(void *) [英] C Question: (const void *) vs (void *)

查看:307
本文介绍了C问题:(const void *)vs(void *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const void *void *有什么区别?在什么情况下可以将void指针强制转换为const void指针?

What's the difference between const void * and void *? Under what circumstances can a void pointer be cast to a const void pointer?

推荐答案

const void *指向不应修改的内存.

A const void * points to memory that should not be modified.

A void *(非常量)指向可以修改的内存(但不能通过void *;您必须先进行转换).

A void * (non-const) points to memory that could be modified (but not via the void *; you'd have to cast it first).

使用memmove()时,源地址强制转换为const void *:

When you use memmove(), the source address is cast to const void *:

void *memmove(void *dst, const void *src, size_t nbytes);

这是一个可以将void指针强制转换为常量void指针的示例.基本上,您可以在知道不打算修改指针所指向的内存时随时执行此操作(转换为常量).这适用于任何指针-不仅是空指针.

That is an illustration when a void pointer can be cast to a constant void pointer. Basically, you can do it (convert to constant) at any time when you know you are not going to modify the memory that the pointer points at. This applies to any pointer - not just void pointers.

以另一种方式转换(从常量指针到非常量指针)是更加危险的练习.无法保证所指向的内存实际上是可修改的.例如,字符串文字可以存储在只读(恒定)内存中,如果使用强制转换丢失了常数,并尝试修改字符串,则可能会遇到分段错误或等效错误-您的程序将突然停止不受您的控制.这不是一件好事.因此,不要在不确定是否可以使用编译器的情况下将指针从常量更改为非常量.请注意,编译器通常在最不方便的时候不喜欢被骗,并且可以收回自己的钱(例如,在老板,老板的老板和老板的老板的老板面前向重要的潜在客户演示程序时) ).

Converting the other way (from a constant pointer to a non-constant pointer) is a much more dangerous exercise. There's no guarantee that the memory pointed at actually is modifiable; for example, a string literal can be stored in readonly (constant) memory, and if you lose the const-ness with a cast and try to modify the string, you will likely get a segmentation fault or its equivalent - your program will stop suddenly and not under your control. This is not a good thing. So, do not change pointers from constant to non-constant without being very sure it is actually OK to lie to your compiler. Be aware that compilers do not like being lied to and can get their own back, usually at the most inconvenient moment (such as when demonstrating your program to an important prospective client in front of your boss, your boss's boss, and your boss's boss's boss).

这篇关于C问题:(const void *)vs(void *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆