I see an article on the cool shell, the C language structure of the member arrays and pointers, I really admire to see the pleasantly surprised ah. Hao elder brother Although honorifics oneself is not a master what, but write such article to, really let me feel my level is slag slag! I read the feeling a little excited, also want to tell me, try to see if you can tell the micro-blog in the description of the problem, absolutely no copy of the meaning. Because my level is really limited, writing may be very bad, but also please forgive me!
OK, talk less, first of all to say a question, there is such a code,
1#include <stdio.h>2 structstr{3 intLen;4 Chars[0];5 };6 7 structFoo {8 structSTR *A;9 };Ten One intMainintargcChar**argv) { A structFoo f={0}; - if(f.a->s) { -printf (f.a->s); the } - return 0; -}
In which line will this program hang up? I'm using GCC, and I'm hanging out here on line 14th. Why is it? Why is the IF statement not hanging out, but hanging out here in the printf statement?
What's the first thing we need to analyze variables? What is the variable, is actually the memory area alias! A struct-type variable, in fact, is a chunk of memory, and then the struct variable name points to the starting address of the memory area, and then continues to roll back other variables based on the type of the variable. Like the STR structure above. is actually a piece of 4 bytes of memory used to hold the int variable len, and then the following bytes to hold the character array S. We can print out their addresses through GDB, as shown in:
The address of the struct variable T and its first member Len is 0xbffff184, and the address of its S member is the address of T +4, which is 0xbffff188. OK, through this narrative do not know whether you can understand, in fact, the structure of each member of the variable address is actually the structure of the variable address plus relative offset. For example, the address of s in the example above is the address of T plus 4 bytes (representing the int variable).
Knowing the concept, let's analyze the procedure.
First, starting with the main function, an F variable is created, a member of which is pointer a, and the address stored in pointer A is initialized to 0. And then in the IF statement using the F.a->s, it is to find an address, is the address of the s variable, looking for the way is to find the structure of the variable pointer a stored in the address, and then to the address +4, and then find the address and not to access the memory space represented by the address, So the program did not error. In the print statement, it is to find this address, and then go to the memory space represented by this address, trying to find a string in this space and output. Since we have initialized to 0 in a, the memory space accessed is 0x4 space, so the program will be hung up! ^ O ^
How does the great God play C language!