简体   繁体   English

指针算法C和强制转换

[英]Pointer arithmetic C and casting

I've seen a very strange code snippet and i am not quite sure if i understood it right: 我已经看到了一个非常奇怪的代码段,但我不确定我是否正确理解该代码段:

#include <stdio.h>

int main(char *argc, char **argv)
{
   char a[50];
   *(char *) (a + 2) = 'b'; // <== THE LINE WHICH CONFUSES ME

   printf("value: %c\n", a[2]);
   return 1;
}

Is it right that we go 2 buckets further cast the 'b' into a pointer to the b and then dereference it? 我们去2个存储桶,进一步将'b'转换为指向b的指针,然后取消引用它,对吗?

That's exactly equivalent of 那完全等于

*(a + 2) = 'b';

The cast is unnecessary. 强制转换是不必要的。

All it does is add two to the array-which-decays-to-a-pointer a , dereference the resulting pointer, and assign the character 'b' to that memory location. 它所做的就是将两个加到数组中,该数组将使指针a衰减,取消对结果指针的引用,并将字符'b'分配给该内存位置。

When a is a pointer, the code a[x] is exactly equivalent of *(a + x) . a是指针时,代码a[x]完全等同于*(a + x) So in your case, *(a + 2) = 'b' is exactly the same as a[2] = 'b' . 因此,在您的情况下, *(a + 2) = 'b'a[2] = 'b'完全相同。

*(char *) (a + 2)

is equivalent to 相当于

a[2]

By definition, a[2] is *(a + 2) . 根据定义, a[2]*(a + 2) The value of a + 2 is already of type char * so a cast of a + 2 to char * , as is (char *) (a + 2) , is a no operation. a + 2值已经是char *类型,因此将(char *) (a + 2)char *a + 2 char *(char *) (a + 2)

  *(char *) (a + 2) = 'b'; // <== THE LINE WHICH CONFUSES ME 

This line literally means the very same as 该行的字面意思与

a[2] = 'b'

The first cast (char*) is redundant, since a is already of type char . 第一个强制转换(char*)是多余的,因为a已经是char类型。 And indexing in fact translates to addition and dereferenciation, ie 实际上,索引转换为加法和解引法,即

a[n] === *(a + n)

A little known fact about C: You could write as well 关于C的鲜为人知的事实:您也可以编写

n[a]

and get the same result. 并获得相同的结果。

You aren't casting the 'b' . 您不是在投射'b'

You cast (a+2) to char* (Which does nothing, since it's already char* ), deference it, and put there 'b' . 您将(a+2) char*char* (不做任何事情,因为它已经是char* ),将其遵从,然后放在'b'

And yes, it is right that we go 2 buckets further. 是的,我们再往前走两个桶是对的。

No, you treat a as a pointer, increment it by two, then cast it to (char*) (useless cast, it already is char* ), dereference it and then store 'b' into that. 不,您将a视为指针,将其递增2,然后将其(char*)(char*) (无用的强制转换,它已经是char* ),取消引用它,然后将'b'存储到该指针中。

It is exactly the same as this: 与此完全相同:

a[2] = 'b';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM