为什么要指定指针类型? [英] Why to specify a pointer type?

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

问题描述

在声明特定类型的指针时实际发生了什么?除了指针算术或索引编制之外,还可以为指针指定类型吗?

What actually happens while declaring a pointer of a specific type? Is there any use to specify a type to a pointer other than pointer Arithmetic or Indexing?

推荐答案

在以下情况下需要使用指针类型

Type of a pointer is needed in following situations

  • 取消引用指针
  • 指针算术

这是取消引用指针的示例.

Here is the example of dereferencing the pointer.

{
    char *ptr; //pointer of type char
    short j=256;
    ptr=&j;    // Obviously You have to ignore the warnings
    printf("%d",*ptr)
}

现在,因为ptr的类型为char,所以它将仅读取一个字节.但是256的二进制值为0000000100000000,但是由于ptr的类型为char,因此它将仅读取第一个字节,因此输出将为0.

Now because ptr is of type char so it will only read one byte. But the binary value of 256 is 0000000100000000 but because ptr is of type char so it will read only first byte hence the output will be 0.

注意:如果我们分配j = 127,则输出将是127,因为127将保留在第一个字节中.

Note: if we assign j=127 then output will be 127 because 127 will be hold by first byte.

现在,以pointer arithmetic为例:

{
    int *ptr;
    int var=0;
    ptr=&var;
    var++;
    ptr++;// pointer arithmetic
}

语句var++ptr++是同一回事吗?不,var++表示var=var+1ptr++表示ptr=ptr+4.因为编译器知道"这是一个指针,并且它指向int,所以它将4加到ptr而不是1,因此指针指向"下一个整数.

Are statements var++ and ptr++ are same thing? No, var++ means var=var+1 and ptr++ means ptr=ptr+4. Because the compiler "knows" this is a pointer and that it points to an int, it adds 4 to ptr instead of 1, so the pointer "points to" the next integer.

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

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