Pranshu_Taneja
Pranshu_Taneja

Reputation: 354

why strlen() function is giving wrong value

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

Upvotes: 2

Views: 796

Answers (2)

John Doe
John Doe

Reputation: 1869

Since your array has length [2][5] you can store a maximum of 2 words of length 4, every word also has the terminating character \0 in addition to its letters.

You having as input heyman means you are writing too many letters and don't have enough space to also store the \0. Either try with a shorter word or change your length from 5 to 7.

Also you are storing 3 words in your array of length 2, the length refers to the number of elements stored not to the number you can go up to. Length 2 will have available positions 0 and 1 so when you are passing as input the third word you are trying to write outside of the array bounds.

Upvotes: 7

Barmar
Barmar

Reputation: 780724

Each row of a is only 5 bytes. When you read heyman into a[0], it overflows into a[1]. So you have:

a[0] = "heyma"
a[1] = "n\0"

Then when you read into a[1], you have

a[0] = "heyma"
a[1] = "jack\0"

Notice that there's no null terminator in a[0]. So when you call strlen(a[0]), it goes past the end of a[0] and continues searching in a[1] for the null byte. There are 5 bytes in a[0] and 4 bytes in a[1], so the length is 9. Technically, this is undefined behavior, but this is what happens in actual implementations because 2-dimensional arrays are contiguous.

In addition, when you read into a[2] you're completely outside the a array, resulting in undefined behavior.

Upvotes: 10

Related Questions