Dave Nguyen Dave Nguyen - 3 months ago 9
C Question

C Programming : for loop and break

Can anybody tell me why the loop does not exit whenever I press letter X? How to make the program not get the value of backspace and enter into the array?

#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#define N 2
#define M 4


int main()
{
int i,j,a[N][M];

for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
scanf("%c",&a[i][j]);
if(a[i][j]=='X')
break;
}
if(a[i][j]=='X')
break;
}
return 0;
}

Answer

There are two problems in your code:

  • The first one is already pointed out by Rishikesh Raje: You need to add a space to the scanf() command in order to eat up the scanned "\n" characters.

  • Then, you scan characters (%c) and try to store them in an int-array. Use

    char a[N][M];
    

    instead. My gcc gives a warning at your erroneous code. Other compilers may silently ignore this.

    Still, in an little-endian-environment (Like PC's) one could think: a char stored at the address of an int-variable should result in the same value. However, the char-value occupies only one byte, the remaining bytes (3 or more) keep uninitialized. If there were zero-bytes before, than a[i][j] will be 'X', otherwise, it will be some random number.

    This explains the behaviour, I think you observed: The program stopped randomly at some 'X' but not always.

Comments