Reputation: 1515
I'll start off with the code I have currently where input is a user provided variable:
int current[2] = {-1, -1}, next[2] = {-1, -1};
char *strtok_result = strtok(input, " ");
int i = 0;
while(strtok_result != NULL){
i++;
int count = 0;
char strtok_buffer[2];
printf("iteration %d-%d: next[0] = %d\n", i, ++count, next[0]);
strcpy(strtok_buffer, strtok_result);
printf("iteration %d-%d: next[0] = %d\n", i, ++count, next[0]);
current[0] = next[0];
current[1] = next[1];
next[0] = strtok_buffer[1] - 48; // ascii conversion, digit to column
next[1] = toupper(strtok_buffer[0]) - 64; // --- || ---, letter to row
printf("iteration %d-%d: next[0] = %d\n\n", i, ++count, next[0]);
strtok_result = strtok(NULL, " ");
}
return 0;
If I enter "A1 B2 C3" I expect the following output:
iteration 1-1: next[0] = -1
iteration 1-2: next[0] = -1
iteration 1-3: next[0] = 1
iteration 2-1: next[0] = 1
iteration 2-2: next[0] = 1
iteration 2-3: next[0] = 2
iteration 3-1: next[0] = 2
iteration 3-2: next[0] = 2
iteration 3-3: next[0] = 3
The output I receive however looks like the following:
iteration 1-1: next[0] = -1
iteration 1-2: next[0] = -256
iteration 1-3: next[0] = 1
iteration 2-1: next[0] = 1
iteration 2-2: next[0] = 0
iteration 2-3: next[0] = 2
iteration 3-1: next[0] = 2
iteration 3-2: next[0] = 0
iteration 3-3: next[0] = 3
It seems to me that somehow, during the execution of *strcpy(strtok_buffer, strtok_result);* the value of next[0] is altered. This boggles me. I have encountered similar results before, and that had to do with memory overlapping (term?), but I cannot see why this would occur here.
Any help is appreciated, I have stared myself blind trying to figure this out.
Notes:
Upvotes: 4
Views: 794
Reputation: 340218
strtok_buffer[2]
is not large enough to hold the tokens "A1"
, "B2"
, or "C3"
. Don't forget that strings need space for the terminating null character.
Upvotes: 5