指针算术(c语言) [英] Pointer arithmetic (c language)

查看:75
本文介绍了指针算术(c语言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解指针算术。



几个例子:



  int  * x =( int  *)0x100; 
x + = 12 ;
// x = 0x130







1.为什么不



  int  * x = 0x100; 





工作?



2.为什么

 * x ++; 

 x + 1; 

在这种情况下相同?



如果有人拥有与此特定案例相关的更多信息的来源,那就太棒了。



我尝试过:



我试过搜索但是没有像上面那样遇到指针算术。

解决方案

 int * x = 0x100; 



这不起作用,因为 x 是一个类型的指针( int * ),而右侧是整数文字( int )。因此,您必须告诉编译器您明确要进行分配。



 * x ++; 

是与

 x + 1不一样; 



第一个可以拆分为:

 * x与x [0]和
x ++相同,与x = x + 1



相同,而第二个是只需

 x + 1 



请注意,第二个版本不会更改 x 而第一个确实如此。



您可以搜索C ++指针算术以了解更多信息。一个好的结果将是 https://www.cs.umd.edu/class /sum2003/cmsc311/Notes/BitOp/pointer.html [ ^ ](请参阅任意指针转换,第一种情况)。


它不起作用因为您正在将指针设置为程序地址空间之外的地址。当您向指针添加数字时,它会将指针指向的类型的项数增加。所以在你的例子中:

  int  * x =( int  *)0x100;  //   x是指向整数的指针 
x + = 12 ; // point x 12整数
/ / 由于每个整数长4个字节
// 添加到x的实际值是4 * 12 = 48
// 或以十六进制0x30
// 所以回答:x = 0x130


I'm having trouble understanding pointer arithmetics.

A few examples:

int *x = (int *)0x100;
x += 12;
//x = 0x130




1. Why doesn't

int *x = 0x100; 



work?

2. Why is

*x++;

the same as

x+1;

in this scenario?

If anyone has a source with more information related to this particular case it would be great.

What I have tried:

I have tried searching but haven't come across pointer arithmetics like the case above.

解决方案

int *x = 0x100;


This won't work because x is a pointer of type (int *) while the right side is an integer literal (an int). So you must tell the compiler that you explicitly want to do the assignment.

*x++;

is not the same as

x+1;


The first can be splitted into:

*x which is the same as x[0] and
x++ which is the same as x = x + 1


while the second is just

x + 1 


Note that the second version is not changing x while the first does.

You may search for "C++ pointer arithmetic" to find out more. One good result will be https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html[^] (see Arbitrary Pointer Casting for your first case).


It won't work because you are setting the pointer to an address that is outside of your program's address space. And when you add a number to a pointer it increments it by the count of items of the type that the pointer is pointing to. So in your example:

int *x = (int *)0x100; // x is a pointer to integers
x += 12;               // point x 12 integers further
                       // and since each integer is 4 bytes long the
                       // actual value added to x is 4 * 12 = 48
                       // or in hex 0x30
// so answer: x = 0x130


这篇关于指针算术(c语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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