当char *已经存在时,为什么需要void *?

时间:2022-09-11 19:48:08

char *, as the original generic pointer, does its job well. As I know, a void * can do nothing more than a char *. What's more, doing arithmetic with void * is not supported by the standard, which is somewhat error-prone.

char *作为原始通用指针,可以很好地完成工作。据我所知,void *只能做一个char *。更重要的是,标准不支持使用void *进行算术运算,这有点容易出错。

So why do we need a void * type in C? And when should we use it, rather than char *?

那么为什么我们需要在C中使用void *类型?什么时候应该使用它,而不是char *?

1 个解决方案

#1


3  

a void * can do nothing more than a char *

一个空虚*只能做一个char *

I'm not sure about which can do more things than another but I'm sure that void* can do his own jobs which char * (or any other type of pointer) cannot.

我不确定哪个可以做更多的事情而不是另一个但我确定void *可以做他自己的工作,其中char *(或任何其他类型的指针)不能。

void* is known as a generic pointer. Generic pointer:

void *被称为通用指针。通用指针:

  • Can hold any type of object pointers
  • 可以容纳任何类型的对象指针

  • Cannot be dereferenced
  • 无法解除引用

  • Especially useful when you want a pointer to point to data of different types at different times
  • 当您希望指针在不同时间指向不同类型的数据时尤其有用

And if you try hard to make char* do something that void* can do, it may possible but will lead to assumption.

如果你努力使char *做一些无效*可以做的事情,它可能会导致假设。

If even the compiler does not inform an error or at least a warning about incompatible type, we still don't want to see this kind of code:

如果连编译器都没有通知错误或至少有关于不兼容类型的警告,我们仍然不希望看到这种代码:

//hi guys, the argument is char* type 
//but you still can pass any other pointer types 
//don't worry!
void func(char * p) {
    ...
}

We just need this:

我们只需要这个:

//this comment is not need, right?
//you know that you can pass any pointer types
void func(void* p) {
    ...
}

#1


3  

a void * can do nothing more than a char *

一个空虚*只能做一个char *

I'm not sure about which can do more things than another but I'm sure that void* can do his own jobs which char * (or any other type of pointer) cannot.

我不确定哪个可以做更多的事情而不是另一个但我确定void *可以做他自己的工作,其中char *(或任何其他类型的指针)不能。

void* is known as a generic pointer. Generic pointer:

void *被称为通用指针。通用指针:

  • Can hold any type of object pointers
  • 可以容纳任何类型的对象指针

  • Cannot be dereferenced
  • 无法解除引用

  • Especially useful when you want a pointer to point to data of different types at different times
  • 当您希望指针在不同时间指向不同类型的数据时尤其有用

And if you try hard to make char* do something that void* can do, it may possible but will lead to assumption.

如果你努力使char *做一些无效*可以做的事情,它可能会导致假设。

If even the compiler does not inform an error or at least a warning about incompatible type, we still don't want to see this kind of code:

如果连编译器都没有通知错误或至少有关于不兼容类型的警告,我们仍然不希望看到这种代码:

//hi guys, the argument is char* type 
//but you still can pass any other pointer types 
//don't worry!
void func(char * p) {
    ...
}

We just need this:

我们只需要这个:

//this comment is not need, right?
//you know that you can pass any pointer types
void func(void* p) {
    ...
}