I am trying to print an element of the cube_pattern
string, but when I execute my code nothing is printed to the console and my code freezes for a few seconds:
#include <stdio.h>
#define SOLVED_CUBE "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB"
char cube_pattern[54] = SOLVED_CUBE
void print_pattern() {
printf("%s", cube_state[0]);
}
void main() {
print_pattern();
}
I tried calling fflush(stdout)
but it still doesn't work:
void print_pattern() {
printf("%s", cube_state[0]);
fflush(stdout);
}
CodePudding user response:
"UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB"
contains 54 characters. Your char array only can store 54 characters. This does not leave space for a null terminator. Thus when you try to print using the %s
specifier, you invoke undefined behavior. Maybe when it looks for the 55th character, it finds 0
, but maybe not.
I don't see that using #define
gains you anything. I would simply:
char cube_pattern[] = "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB";
CodePudding user response:
Your code has multiple errors. First, you have multiple typos. For example, cube_state
should be cube_pattern
. Second, you are using the printf()
formatter %s
, but only passing it one character (cube_pattern[0]
). Lastly, your array is only 54 bytes long, but your string needs 55 bytes (54 characters one NULL character).
This code works for me:
#include <stdio.h>
char cube_pattern[55] = "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB";
void print_pattern() {
printf("%s\n", cube_pattern);
}
int main() {
print_pattern();
}
I have also changed printf("%s", cube_pattern);
to printf("%s\n", cube_pattern);
. Adding a new line will flush the buffer if your output is line-buffered, which is generally what you want. Alternatively, you could also use fflush(stdout)
.