C language (invalid pointer)! I thought I had mastered C, but I didn’t expect to be on the first level!

Time:2021-12-30

I used to think that C language was deep into the bone marrow for me, and all the grammatical details were already familiar to me. I didn’t understand it until I met a written test question, a crazy written test question.

Pattern, Tucson! Hey, I’m still too young.

 

The code of the original question is complex and I can’t remember it, but the key grammar points of the assessment are as follows:

//Invalid pointer

int main(void)

{

void (*p)(); // Defines a pointer

   int a = 100;

p = &a; / / make the pointer P point to a

printf(“a: %d\n”, *p); // Output the value of the target of P (i.e. a)

}

Here are the output results:

a: – 3495729482452 (garbled)

 

The output result is obviously a garbled code, but what is this garbled code? We will modify the source code slightly:

//Invalid pointer

int main(void)

{

void (*p)(); // Defines a pointer

   int a = 100;

p = &a; / / make the pointer P point to a

printf(“&a: %#x\n”, &a); // Output the address of a in hexadecimal

printf(“*p: %#x\n”, *p); / / output the value of the target of P (i.e. a) in hexadecimal

}

Here are the output results:

&a:0xbfb4788

*p: 0xbfb4788

The two outputs are exactly the same! You know, the address of a is stored in P, that is, P is equal to 0xbfb4788, but * P should be the target of P, that is, 100, but why is it still an address?

 

Change the code again:

//Invalid pointer

int main(void)

{

void (*p)(); // Defines a pointer

   int a = 100;

p = &a; / / make the pointer P point to a

printf(“p: %#x\n”, p); / / output the address stored by pointer P in hexadecimal

printf(“*p: %#x\n”, *p); / / output the target of pointer P (i.e. a) in hexadecimal

printf(“**p: %#x\n”, **p); / / output something that should not be output!

}

Here are the output results:

p: 0xbfb4788

*p: 0xbfb4788

**p:0xbfb4788

 

I can’t believe my eyes. In this code, the pointer P seems to be evil, and the dereference * doesn’t work on it. No matter how many * are added in front of P, I can’t get the target of P, that is, the value of a!

What’s going on? Little buddy, be as smart as you. Write your opinions into the message and give it to everyone for reference!

 

If you want to study deeplyC language and advanced programming——Programming Club[enter as shown below]!

It involves: C language, C + +, windows programming, network programming, QT interface development, Linux programming, game programming, hackers and so on

 

Introduction to programmer programming:

 

2. Recommended books for programmers:

 

An active, high-level programmer programming learning hall; The introduction to programming is only incidental, and the improvement of thinking is valuable!