pointer-arithmetic

Pointer Arithmetic In C

情到浓时终转凉″ 提交于 2019-11-26 02:14:45
问题 Consider the following code fragment: int (*p)[3]; int (*q)[3]; q = p; q++; printf(\"%d, %d\\n\", q, p); printf(\"%d\\n\", q-p); I know that pointer arithmetic is intelligent, meaning that the operation q++ advances q enough bytes ahead to point to a next 3-integers-array, so it does not surprises me that the first print is \' 12, 0 \' which means that incrementing q made it larger in 12. But the second print does surprises me. It prints 1! So why would it print 1 instead of 12? it just

C/C++: Pointer Arithmetic

∥☆過路亽.° 提交于 2019-11-26 01:35:10
问题 I was reading a bit in Pointer Arithmetic, and I came upon 2 things I couldn\'t understand neither know it\'s use address_expression - address_expression and also address_expression > address_expression Can someone please explain them to me, how do they work and when they are used. Edit: What I meant to say is what do they produce if I just take two addresses and subtract them And If I take two addresses and compare them what is the result or comparing based upon Edit: I now understand the

Pointer Arithmetic [closed]

*爱你&永不变心* 提交于 2019-11-25 22:19:13
问题 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++. 回答1: 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

Pointer arithmetic for void pointer in C

独自空忆成欢 提交于 2019-11-25 22:02:11
问题 When a pointer to a particular type (say int , char , float , ..) is incremented, its value is increased by the size of that data type. If a void pointer which points to data of size x is incremented, how does it get to point x bytes ahead? How does the compiler know to add x to value of the pointer? 回答1: Final conclusion: arithmetic on a void* is illegal in both C and C++. GCC allows it as an extension, see Arithmetic on void- and Function-Pointers (note that this section is part of the "C

With arrays, why is it the case that a[5] == 5[a]?

那年仲夏 提交于 2019-11-25 21:35:09
问题 As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a] Joel says that it\'s because of pointer arithmetic but I still don\'t understand. Why does a[5] == 5[a] ? 回答1: The C standard defines the [] operator as follows: a[b] == *(a + b) Therefore a[5] will evaluate to: *(a + 5) and 5[a] will evaluate to: *(5 + a) a is a pointer to the first element of the array. a[5] is the value that's 5 elements