指针运算 [英] Pointer Arithmetic

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

问题描述

有没有人有指针运算任何好文章或解释(博客,例子)?图观众是一堆Java程序员学习C和C ++的。

Does anyone have any good articles or explanations (blogs, examples) for pointer arithmetic? Figure the audience is a bunch of Java programmers learning C and C++.

推荐答案

首先,宾基视频可能会有所帮助。这是关于一个三分球不错的视频。对于算术,这里是一个例子:

First, the binky video may help. It's a nice video about pointers. For arithmetic, here is an example:

int * pa = NULL;
int * pb = NULL;
pa += 1; // pa++. behind the scenes, add sizeof(int) bytes
assert((pa - pb) == 1);

print_out(pa); // possibly outputs 0x4
print_out(pb); // possibly outputs 0x0 (if NULL is actually bit-wise 0x0)

<子>(注意,递增包含一个空指针值严格的指针是未定义的行为。我们使用空,因为我们只在指针的值感兴趣。通常,只指向的元素时,使用递增/递减一个数组)。

以下显示了两个重要的概念

The following shows two important concepts


  • 加成/一个整数的指针的减法装置由N个元素将指针向前/向后。所以,如果一个int为4个字节大,PA可能已经加1后包含我们的平台上为0x4。

  • 将另一个指针的指针的减法手段让他们的距离,通过测量元素。因此,从PA PB减去将产生1,​​因为他们有一个元素的距离。

在一个实际的例子。假设你写一个函数和人民为您提供一个起点和终点指针(在C ++中很平常的事):

On a practical example. Suppose you write a function and people provide you with an start and end pointer (very common thing in C++):

void mutate_them(int *begin, int *end) {
    // get the amount of elements
    ptrdiff_t n = end - begin;
    // allocate space for n elements to do something...
    // then iterate. increment begin until it hits end
    while(begin != end) {
        // do something
        begin++;
    }
}

ptrdiff_t的是什么(结束 - 开始)的类型。它可以是用于INT对于一些编译器的同义词,而可以是另一种类型的另外一个。人们可以不知道,所以一个人选择通用的typedef ptrdiff_t的

ptrdiff_t is what is the type of (end - begin). It may be a synonym for "int" for some compiler, but may be another type for another one. One cannot know, so one chooses the generic typedef ptrdiff_t.

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

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