什么是空指针,什么是空指针? [英] What is a void pointer and what is a null pointer?

查看:119
本文介绍了什么是空指针,什么是空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到了一些面试问题,遇到了

So I was going through some interview questions and I came across one about void and null pointers, which claims:

没有返回类型的指针称为空指针.它可以是任何一种数据类型.

a pointer with no return type is called a null pointer. It may be any kind of datatype.

这使我彻底困惑了!根据这个问题,似乎可以将null和null互换使用,我不认为这是正确的.我以void为返回类型,以null为值.但是我只是一个代码新手,不确定我是对的.

This confused me thoroughly! It seems void and null could be used interchangeably according to this question, and I don't believe that to be correct. I assumed void to be a return type and null to be a value. But I am just a code-rookie and am not sure I am right.

请表达您对空指针和空指针的看法.我不是在寻找null和void之间的区别.

Please express your views as to what a null pointer is and a void pointer is. I am not looking for difference between null and void.

推荐答案

两个概念是正交的:

  1. 无效指针(void *)是指向某些内存位置的原始指针.
  2. 根据定义,空指针是一种不指向任何东西的特殊指针.它可以是指向任何类型(无效或其他类型)的指针.
  1. A void pointer, (void *) is a raw pointer to some memory location.
  2. A null pointer is a special pointer that doesn't point to anything, by definition. It can be a pointer to any type, void or otherwise.

无效指针可以为null或不为空:

A void pointer can be null or not:

void *void_ptr1 = nullptr;
void *void_ptr2 = malloc(42);
void *void_ptr3 = new Foo;               // void * can point to almost anything
void *void_ptr4 = (char*)void_ptr3 + 1;  // even somewhere inside an object

非空指针也可以为null:

A non-void pointer can also be null or not:

Foo *f = nullptr;
Foo *g = new Foo;

这篇关于什么是空指针,什么是空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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