为什么我[ARR]工作,以及改编[i]于具有较大的数据类型C 2 [英] Why does i[arr] work as well as arr[i] in C with larger data types?

查看:221
本文介绍了为什么我[ARR]工作,以及改编[i]于具有较大的数据类型C 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是相当普遍的知识,如果你用C访问数组中的元素作为改编[I] ,您也可以访问该元素为我[ARR] ,因为这些只是归结为 *(ARR + I)和加法是可交换的。我的问题是,为什么这个工程的数据类型比字符大,因为的sizeof(char)的 1,对我这应该只由一个字符前进指针。

It's fairly common knowledge that if you access an element of an array as arr[i] in C that you can also access the element as i[arr], because these just boil down to *(arr + i) and addition is commutative. My question is why this works for data types larger than char, because sizeof(char) is 1, and to me this should advance the pointer by just one char.

也许这个例子使得它更清晰的:

Perhaps this example makes it clearer:

#include <string.h>
#include <stdio.h>

struct large { char data[1024]; };

int main( int argc, char * argv[] )
{
    struct large arr[4];
    memset( arr, 0, sizeof( arr ) );

    printf( "%lu\n", sizeof( arr ) ); // prints 4096

    strcpy( arr[0].data, "should not be accessed (and is not)" );
    strcpy( arr[1].data, "Hello world!" );

    printf( "%s, %s, %s\n", arr[1].data, 1[arr].data, (*(arr+1)).data );
    // prints Hello world!, Hello world!, Hello world!
    // I expected `hold not be accessed (and is not)' for #3 at least

    return 0;

}

那么,为什么加一个数组指针推进它通过的sizeof(结构大)

推荐答案

在C,指针运算的定义,这样写

In C, pointer arithmetic is defined so that writing

ptr + k

不被K推进指针的字节,但用k 对象。因此,如果你有一个指向整数数组,写

does not advance the pointer by k bytes, but by k objects. Thus if you have a pointer to an integer array and writing

*(myIntArrayPointer + 3)

您在索引3的阵列,而不是开始的三个字节过去的对象的开始的整数解引用一个指针的元素

You are dereferencing a pointer to the element at index 3 in the array, not the integer that starts three bytes past the start of the object.

同样,如果您的减去的两个指针,你在他们之间,而不是字节总数元素的逻辑编号。这样写

Similarly, if you subtract two pointers, you get the logical number of elements in-between them, not the total number of bytes. Thus writing

(myIntArrayPointer + 3) - myIntArrayPointer

得到值3,即使有 3 * sizeof的(INT)字节,在他们之间。

希望这有助于!

这篇关于为什么我[ARR]工作,以及改编[i]于具有较大的数据类型C 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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