I'm a beginner in C language. Below is the code with the bug.
#include<stdio.h>
int main(void){
int repeat;
int value 1 = 0;
int value2 = 0;
intv;
int add;
char command [10];
char str[3];
scanf("%d", & repeat);
inti;
for(i=0;i<repeat;i=i+1){
scanf("%s%d%d", & command, & v, & add);
if(command=="SET"){
if(v==1){
value1+=add;
printf("%s%d%d\n", command, value1, value2);
// Here, if add is entered as SET 110, add == 1. Moreover, value 1 == -1. (It should be value 1 + = add, but subtracted backwards.)
}
else{
printf("%d",v);
value2+=add;
printf("%s%d%d\n", command, value1, value2);
// Here, for example, if you enter SET 220, add==2 is subtracted from value1 to make value1==-3.
}
}
else if(command=="ADD"){
The following is omitted from here.
I don't know why these bugs occur.
I think the cause of this series of bugs is the add, could you tell me more about it?
For now, I'm concerned that I compare char[] with ==.
If it's C language, how about strcmp?
You may want to check if the debugger is properly running the problem.
char command [10];
scanf("%s%d%d", & command, & v, & add);
%s
in scnaf
requests the first address of the string, where &command
is the address of the variable containing the first address.The correct value is command
.
Most compilers should warn you that the arguments are incorrectly specified correctly.wandbox
prog.c:In function 'main':
prog.c:17:17:warning:format'%s' expectations argument of type 'char*', but argument2 has type 'char(*)[10]'[-Wformat=]
17 | scanf("%s%d%d", & command, & v, & add);
| ~^ ~~~~~~~~
| | |
| char*char(*) [10]
prog.c:18:21:warning:comparison with string literal results in unspecified behavior [-Waddress]
18 | if(command=="SET"){
| ^~
(As Jogenara pointed out, string comparison is also strange.)
© 2024 OneMinuteCode. All rights reserved.