Pointer operators and pointer expressions

Source: Internet
Author: User
Tags printf

6.3.1 pointer operators and pointer expressions

There are two operators on pointers in C:

& Operator: Takes the address operator, &m is the address of the variable m.

* Operator: pointer operator, *PTR represents the variable to which it is pointing.

[Example 6-2] Enter two integers from the keyboard and output in order from large to small.

main()
{
int *p1,*p2,a,b,t;/*定义指针变量与整型变量*/
scanf("%d,%d",&a,&b);
p1=&a;/*使指针变量指向整型变量*/
p2=&b;
if(*p1<*p2)
{/*交换指针变量指向的整型变量*/
t=*p1;
*p1=*p2;
*p2=t;
}
printf("%d,%d\n",a,b);
}

In the program, when the assignment operation P1=&a and P2=&b, the pointer actually points to the variable A and B, then the reference pointer *p1 and the *P2, which represents the variable A and B. To run the program:

RUN
3,4
4,3

As the program runs, the relationship between the pointer and the variable you are referring to is shown in Figure 6-4:

When the pointer is assigned to the memory as a), when the data is compared to exchange, when the pointer variable and the variable to point to the relationship between the same as B, in the process of running the program, the pointer variable and the variable pointing to the constant. The following changes are made to the program.

[Example 6-3]

main()
{
int*p1,*p2,a,b,*t;
scanf("%d,%d",&a,&b);
p1=&a;
p2=&b;
if(*p1<*p2)
{/*指针交换指向*/
t=p1;
p1=p2;
p2=t;
}
printf("%d,%d\n",*p1,*p2);
}

The program runs exactly the same, but when the program is running, the data actually stored in memory does not move, but instead the pointer to the variable is exchanged. The schematic diagram is shown in Figure 6-5:

When the pointer switches to point, P1 and P2 change from the original point of the variable A and B to point to variable B and a, so that *P1 represents variable B, and *P2 represents variable a. In the above program, whenever the pointer and the variable being pointed to satisfy p=&a;, we can represent the variable a as a pointer. At this point P is equivalent to &a,*p equivalent to variable a.

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.