First look at the topic, the following program will crash in that line, the program is as follows:
#include <iostream>using namespace std;struct s{int i;int *p;}; int main () {S S;int *p = &s.i;p[0] = 4;p[1] = 3;S.P = p;s.p[1] = 1;s.p[0] =2;return 0;}
Although the program is very short, but to understand clearly, it is not easy, first of all, a few knowledge points:
1. For struct structure, the space allocated by it is continuous;
2.p[0] Represents the value of the address stored in P, and the use of such questions as P[0] is mentioned below;
Now start interpreting the program:
First, *p=&s.i, represents p storage s.i address, below to p[0] = 4, then the address to P is assigned to a value of 4, that is, s.i = 4; then p[1],p[1] represents the next address of P point of address, in the structure of the address is continuous, so p[1] It also points to the next address that P points to, that is, the next address of S.I, which is S.P, to p[1] Assignment is to assign a value to S.P, S.P is the pointer type, so in hexadecimal notation, so S.P is 0x3; The following is S.P point to the P pointer (here two p a bit around the mouth, but always remember the structure of P front with s), then S.P point to the address that P points to, that is, S.I, the following is S.P [1] = 1, that is, to give S.P to the address of the next address assignment, that is, to s.i the next address assignment, that is, to assign their own value, so that their values are assigned to 0x1, that is, S.P point to 0x1 this address, the following to s.p[0] = 2; This is to give S.P point to the address assignment, this can be successful? Of course not, what is the address s.p points to? Is 0x1 This is a non-declarative space, so the program will access errors, that is, in s.p[0]=2;
Let's look at one more question about p[0]:
The result? Is 6, why? The address of the a[2], as we all know, the function of the array to do formal parameter transfer is the first address of the array, so also understand, probably similar to a[2] =a[1] +a[3];
C + + pointer classic problem analysis