Solving Aizu Online Judge ALDS1_3_C.
I'm worried about an unknown cause error.Here's the source code:
Now, if you declare a variable of type structure job in the main function, the scanf function will not receive input.As a trial, I commented out the while statement of the main function and received it when I ran it.If you declare a variable of type structure job within the main function, the second scanf function will not receive input immediately.Please tell me the solution.c algorithm
I think it's a side effect of the so-called memory corruption.
command is a pointer and has not been initialized, the results of
scanf() are stored in an unusual location, and subsequent operations are not expected to work properly.
Declare the variable
command as an array or modify it to point to areas dynamically reserved by
Also, the following comparison statement is also incorrectly implemented, so I think it is necessary to compare strings with
First of all, making the corrections as described below will not result in your code acting as a queue as expected.
(If I correct it while explaining everything, it will be an ultra-long sentence that almost directly translates the description of the pointer in the C language textbook and the description of the double link queue in the data structure textbook, so I focused on the uninitialized pointer.)
For the time being, this line in
main is fatal.
Now you have declared the
command as a pointer of type
char*, but you have never initialized the value of this pointer before rewriting the pointer reference.
command remains uninitialized, you have no idea where the memory in the system is pointing.Running
scanf as it is will destroy some memory in the system.The behavior of declaring a variable of type structure job in the main function has changed, but it just happens that some memory will break the moment the
scanf above runs even once, and subsequent behavior will be unpredictable (and, in bad luck, it may seem to be working).
A declaration of the
main should, for example, be as follows:
There are other parts of your code that use uninitialized pointers.
new in the
insert function is declared as a pointer of type
structure cell* but has not been initialized again.You should not place addresses that will be stored on other pointers in a local array, so
malloc should dynamically allocate space.
(Of course, the allocated memory should be released somewhere.)
- I use
== instead of
strcmp for string comparison (second half of user20098's answer)
malloc size calculation for string (
structure cell) is incorrect
You'll have to rewrite everywhere to keep things moving.
Correcting the above undefined pointer references should stabilize the operation a little bit, so please remove the problem little by little.
© 2022 OneMinuteCode. All rights reserved.