C Language pointer subtraction problem

Source: Internet
Author: User

Today, my classmate asked me a pointer subtraction problem, originally did not think carefully, record the relevant experience, thank the classmate

The source code is as follows:

1#include <stdio.h>2 3 intMain ()4 {5 6     inta[]={0,1};7     int*p,*Q;8 9 Tenp=&a[0]; Oneq=&a[1]; A  -printf"%x%x\n\n", p,q); -  theprintf"%x\n\n", Q-p); -  -     return 0; -}

The second line of output found to be 1, the classmate said that since an int accounted for 4 bytes, and the pointer output address is also a difference of four bytes, but why the subtraction will output 1?

I don't know, then, to test, to improve the code, to change the int type to char (char to one byte), the output is the same, the difference is 1.

Why is it?

To improve the original code, add an int type M variable, (in fact, it should be obvious that the problem, but not notice, so look down)

The value of the local variable m is viewed at the VS2012 breakpoint, and it is found that:

So, finally found the problem.

The addition and subtraction of pointers is handled in the C language (subject only, others regardless):

Such as:

int *ptr;

Ptr+n;

Then the compiler does the following:

Add the address of the pointer to n sizeof (the type of the pointer), in this case, sizeof (int);

So no matter what type of pointer it is, the result of the addition and subtraction is necessarily a number of integers (of course, if it makes sense, if two pointers are not relevant you are useless);

So, the addition and subtraction of pointers is the calculation of the whole number of sizeof (pointer type) on the basis of the original pointer, so the result must be an int, (of course, within the range of int).

That's what I think. Thanks to the following authors, refer to the link:

Http://blog.chinaunix.net/uid-24784130-id-2578030.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.