为什么将 void 指针增加 1 会向前移动 1 个字节,但对于整数指针则是 4 个字节,对于 double 则是 8 个字节? [英] Why does incrementing a void pointer by 1 moves one byte ahead but it's 4 bytes for an integer pointer,8 for double?

查看:123
本文介绍了为什么将 void 指针增加 1 会向前移动 1 个字节,但对于整数指针则是 4 个字节,对于 double 则是 8 个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,如果我给空指针加 1,它将向前移动一个字节.但是,正如预期的那样,它分别为 intdouble 移动了 4 个和 8 个字节 指针.为什么空指针移动 1 个字节,就像字符指针一样?

In the following program,if I add 1 to a void pointer, it moves one byte ahead.But,quite as expected, it moves 4 and 8 bytes respectively for int and double pointers.Why does the void pointer move by 1 byte,just as a character pointer would?

#include<stdio.h>

int main(void)
{

        int num=3,*int_ptr=&num;
        double sum=3,*double_ptr=&sum;
        void *void_ptr1=&num,*void_ptr2=&sum;
        printf("%p,%p,%p,%p,%p,%p,%p,%p",void_ptr1,void_ptr1+1,\
        void_ptr2,void_ptr2+1,int_ptr,int_ptr+1,double_ptr,double_ptr+1);
}

推荐答案

您不能对 void 指针进行指针运算(因为它没有意义).可能只是你的编译器有一个扩展,允许对空指针执行指针算术,它是这样实现的.但是,它既不标准也不鼓励使用.

You can't do pointer arithmetic on a void pointer (because it doesn't make sense). Probably it's just that your compiler has an extension that allows pointer arithmetic to be performed on void pointers, and it's implemented like this. However, it is neither standard nor encouraged to be used.

这篇关于为什么将 void 指针增加 1 会向前移动 1 个字节,但对于整数指针则是 4 个字节,对于 double 则是 8 个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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