Reputation: 5672
I have an input()
function which simply compares a string (of 2 characters length) passed to it and returns corresponding integer by comparing that string with some pre-set strings:
int input(char *ch){
if(strcmp(ch, "AZ") == 0){
return 1;
}
else if(strcmp(ch, "BY") == 0){
return 2;
}
else if(strcmp(ch, "CX") == 0){
return 3;
}
}
I have an input set with several test cases (Each case starts with an integer N
, and subsequent N
inputs contain some strings. The test cases ends with a value of N
as 0
):
2
AZ BY
2
AZ CX
1
AZ
3
AZ CX AZ
4
BY AZ CX BY
0
The correct output should be:
1 2 1 3 1 1 3 1 2 1 3 2
Then, I was trying to run below code for getting output:
int main()
{
int i, j, N, array[100];
char ch[2];
while((scanf("%d", &N) == 1) && N != 0){
for(i=0; i<N; i++){
scanf("%s", ch);
array[i] = input(ch);
printf("%d ", array[i]);
}
}
return 0;
}
The code above came with the accurate outputs. But when the code below is run, the output is wrong:
int main()
{
int i, j, N, array[100];
char ch[2];
while((scanf("%d", &N) == 1) && N != 0){
for(i=0; i<N; i++){
scanf("%s", ch);
array[i] = input(ch);
}
for(j=0; j<N; j++){
printf("%d ", array[j]);
}
}
return 0;
}
Output for the 2nd snippet is:
0 2 0 3 1 0 3 1 0 1 3 2
I couldn't even guess what is the fundamental difference between those two snippets and why the outputs are different in those two cases. In 2nd code, I've used same iteration of the for loop and I guess, the array should still hold the values assigned in the 1st for loop. No other statements are manipulating the values of array[]
in between the two for loops. Then, why
the dissimilar outputs? Someone please help me on this issue.
Upvotes: 1
Views: 155
Reputation: 223699
A string in C is a sequence of characters followed by a terminating null byte. So to store a two character string you need an array at least 3 elements long.
Your array only holds 2. As a result, writing a 2 character string to the array writes past the end of the array when the null byte is written. Writing past the end of an array invokes undefined behavior. A consequence of this is that the code might appear to run correctly but a seemingly unrelated change could cause the results to change or even a crash.
Make your array at least 3 characters long.
char ch[3];
Upvotes: 3