I need to get the first item from an string arrays in C, this is my code:
#include <stdio.h>
#include <string.h>
int main() {
char *codes[16] = {
"VVVV", "VVVB", "VVBV", "VVBB", "VBVV", "VBVB", "VBBV", "VBBB",
"BVVV", "BVVB", "BVBV", "BVBB", "BBVV", "BBVB", "BBBV", "BBBB"
};
char code[4];
int ret = 0;
int j = 0;
printf("Enter code to search: ");
scanf("%s", code);
for (j = 0; j < 16; j++) {
printf("\ncode to search is: %s, j value: %d, codes[j]: %s",
code, j, codes[j]);
ret = strcmp(code, codes[j]);
if (ret == 0) {
printf("\nValue of index: %d\n", j);
}
}
}
When I enter the first code to search (VVVV) I get a void value in position 0, and It doesn't return the index 0. Another values works but the first doesn't.
This is the output:
Enter code to search: VVVV
code to search is: VVVV, j value: 0, codes[j]:
code to search is: VVVV, j value: 1, codes[j]: VVVB
code to search is: VVVV, j value: 2, codes[j]: VVBV
code to search is: VVVV, j value: 3, codes[j]: VVBB
code to search is: VVVV, j value: 4, codes[j]: VBVV
code to search is: VVVV, j value: 5, codes[j]: VBVB
code to search is: VVVV, j value: 6, codes[j]: VBBV
code to search is: VVVV, j value: 7, codes[j]: VBBB
code to search is: VVVV, j value: 8, codes[j]: BVVV
code to search is: VVVV, j value: 9, codes[j]: BVVB
code to search is: VVVV, j value: 10, codes[j]: BVBV
code to search is: VVVV, j value: 11, codes[j]: BVBB
code to search is: VVVV, j value: 12, codes[j]: BBVV
code to search is: VVVV, j value: 13, codes[j]: BBVB
code to search is: VVVV, j value: 14, codes[j]: BBBV
code to search is: VVVV, j value: 15, codes[j]: BBBB
What could be wrong?
char code[4]) is not big enough to hold a string likeVVVVbecause there's no room for the NUL terminator. So after you typeVVVVto thescanf, you have a buffer overrun and undefined behavior. After that, anything can happen...