I don't understand why strlen() is giving wrong value (ie: 9) only for the first string. After that the values are coming correctly.
#include <stdio.h>
#include <string.h>
int main() {
int m, i, j;
i = 2;
j = 5;
char a[i][j];
for (i = 0; i <= 2; i++) {
scanf("%s", a[i]);
}
m = strlen(a[0]);
printf("%d\n", m); //here the problem is coming//
m = strlen(a[1]);
printf("%d\n", m);
m = strlen(a[2]);
printf("%d\n", m);
return 0;
}
INPUT:
heyman
jack
bro
OUTPUT:
9
4
3
4characters becausej == 5.heymanis writing out of bounds.j=5will give you 5 characters to write, from0to4, but strings need to have an additional character\0at the end otherwiseCdoesn't know that the string is actually over. That means that from your maximum length you have to subtract1to account for this terminator\0a[5]means you have positionsa[0], a[1], a[2], a[3], a[4]available, i.e.5spaces not that the array will go up toa[5]a[2]has only 2 elements with index0..1.