Joke Collection Website - Joke collection - An incomprehensible problem in C++
An incomprehensible problem in C++
You and your colleagues don’t understand it quite right
Let’s differentiate:
char *p="sdfjsd";
char p[7]="sdfjsd";
char *p="sdfjsd";
The compiler will optimize and save "sdfjsd" in the constant area," sdfjsd" is also used as a constant,
and p points to the first address of this constant string.
So *p='a' means assigning a value to the constant area, so an error is reported.
char p[7]="sdfjsd";,
The compiler allocates 7 char type continuous address spaces in the stack area,
and p Points to the first address of this stack area.
So *p='a' means assigning value to the stack area, no problem.
Let’s talk about another difference:
char *p="sdfjsd";
char *q="sdfjsd";
Written like this, p and q actually point to the same address.
As I just said, for constant strings, the compiler will optimize and save only one "sdfjsd" in the constant area.
p>So p and q point to the same address
char p[7]="sdfjsd";
char q[7]="sdfjsd";
p>
Written like this, p and q point to different addresses. This is relatively simple, so I won’t go into details
================== ==============
Question supplement: In fact, I also think that "sdfjsd" is a constant string, so there will be an exception when assigning a value to it, but if so , why doesn’t the compiler report an error during compilation instead of waiting until runtime to report an exception? For example, the compiler can require us to use a Const type pointer to reference during initialization, const char *p="sdkfjls ";
===============================
The compiler does not It's so smart,
If you use a code static analysis tool (for example: QAC), you can find it out.
- Related articles
- Complete works of funny and domineering quotations
- Is there pure friendship between men and women?
- It is said that science has no academic field. What can prove this?
- Tell some funny jokes. 2
- I was scratched by my pet dog's paw and bled. Do I need to be vaccinated?
- Reflections on space teaching
- ?Interview skills—interview inspirations from interview stories
- Li's four misers in China
- Sixth grade composition in "Huanggang": Use a specific example to illustrate a point of view to imitate "Truth is born after a hundred question marks. Please help, fellow sixth graders"
- What is the clown's national dictionary?