Hello everyone!
I have a problem, which seems like a compiler error to me.
I posted my solution of “Power of Thor” below, which works 100% even though I think it shouldnt. The problem is the following line:
char move[1];
This line should declare as far as I know an array of char with only one element. But this array holds 2 chars, which I can read and write without problems.
In an earlier version of the code the line was:
char move[2];
This declared an array with 3 (!) chars, which lead to problems, because the complete string would have unwanted values in char[2]. Only 2 chars are necessary for the solution of this puzzle.
Am I wrong with thinking that char move[i] declares an array with i chars?
Interestingly “sizeof(move)” gives the value, that I think of as being correct.
In case you want to check the code yourself, here is the complete code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
int lightX; // the X position of the light of power
int lightY; // the Y position of the light of power
int initialTX; // Thor’s starting X position
int initialTY; // Thor’s starting Y position
scanf("%d%d%d%d", &lightX, &lightY, &initialTX, &initialTY);
// game loop
while (1) {
int remainingTurns; // The remaining amount of turns Thor can move. Do not remove this line.
char move[1]; // Strange, I thought this would initialize only one char :O
scanf("%d", &remainingTurns);
// resets move
for (int i = 0; i<2; i++) {
move[i] = NULL;
}
// Write an action using printf(). DON'T FORGET THE TRAILING \n
// To debug: fprintf(stderr, "Debug messages...\n");
// Y-Axis
if (initialTY < lightY) {
move[0] = 'S';
++initialTY;
} else if (initialTY > lightY) {
move[0] = 'N';
--initialTY;
}
// X-Axis
if (initialTX < lightX) {
move[1] = 'E';
++initialTX;
} else if (initialTX > lightX) {
move[1] = 'W';
--initialTX;
}
// move[0] can't be empty
if (move[0] == NULL) {
move[0] = move[1];
move[1] = NULL;
}
fprintf(stderr, "move[0]: %c\n",move[0]);
fprintf(stderr, "move[1]: %c\n",move[1]);
fprintf(stderr, "move before printing: %s\n",move);
fprintf(stderr, "size of move: %d\n",sizeof(move));
// A single line providing the move to be made: N NE E SE S SW W or NW
printf("%s\n",move);
}
return 0;
}