* Temp ++ = 1 problem

Source: Internet
Author: User
#include "stdafx.h"#include"stdio.h"int main(int argc, char* argv[]){int *temp;int b=99;temp=&b;printf("temp is:%d\n",temp);printf("b is:%d\n",b);printf("b's addr is:%d\n\n",&b);*temp++=1;printf("temp is:%d\n",temp);printf("b is:%d\n\n",b);*temp++=1;printf("temp is:%d\n",temp);printf("b is:%d\n",b);return 0;}

 

Program running result:

Apparently, an exception occurs after the second execution of ++ in temp.

 

Modify the program as follows:

#include "stdafx.h"#include"stdio.h"int main(int argc, char* argv[]){int *temp;int b=99;temp=&b;printf("temp is:%d\n",temp);printf("b is:%d\n",b);printf("b's addr is:%d\n\n",&b);*temp++=1;printf("temp is:%d\n",temp);printf("b is:%d\n\n",b);temp++;printf("temp is:%d\n",temp);printf("b is:%d\n",b);return 0;}

 

Running result:

After modification, the program runs as expected.

 

Summary:

1. * temp ++ = 1 is interpreted as * temp = 1; temp ++;

2. A pointer points to an integer variable and performs the pointer ++ operation on the pointer. The value of the pointer has changed 4, not 1;

3. After the pointer value is changed, it points to a new address. If the new address is never declared as the address of any variable in the entire program, you cannot use the * operator to modify the content of this address.

 

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.