This code doesn't even compile. The main problem is here:
char[] apples = moves;
This is invalid syntax. If you want to declare an array, the []
goes after the identifier, like char apples[]
.
Even when corrected, a pointer (moves
) is not a valid initializer for an array:
- When you leave out the dimension of the array in the declaration, the dimension must be deduced from the initializer. This is impossible with just a pointer, there's no size information in a pointer.
- Assigning an array is not possible in C.
If you really want to copy a string to a char
array, you'd have to do something like this:
char apples[strlen(moves) + 1]; // one extra byte for terminating 0
strcpy(apples, moves);
This uses a variable-length array, which was introduced in C99, is optional in C11, but supported by most compilers. For alternatives, please do some research yourself.
Additionally, this line doesn't do what you probably think it does:
if (a && b == 0) {return true;}
The condition is evaluated as a && ( b == 0 )
. If a
is not 0, this is logically true, so the whole expression is true exactly when a is not 0 and b is 0. You seem to want:
if (a == 0 && b == 0) {return true;}
What's really uhm ... "surprising" ... about the code is the fact that the array serves no purpose at all. You could just directly access the characters through moves
without ever taking a copy:
bool judgeCircle(char* moves) {
int a = 0;
int b = 0;
for (int i = 0; i < strlen(moves); i++)
{
if (moves[i] == 'U') { a++;}
if (moves[i] == 'D') { a--;}
if (moves[i] == 'L') { b--;}
if (moves[i] == 'R') { b++;}
}
if (a == 0 && b == 0) {return true;}
else {return false;}
}
This doesn't change anything about the semantics of the function, but just leaves out the one part that you got completely wrong.