0
#include <stdio.h>

int main(void) {
    char strp[] = "hello";
    char strq[] = " world";
    strcat(strp,strq);
    puts(strp); //hello world
    printf("%d",sizeof(strp)-1);//this gives 5(length of 'hello' -1 for '\0')
    printf("%d",strlen(strp));//gives correct answer(11)
    return 0;
}

Why does sizeof give wrong answer but strlen give right answer in this case?

0

2 Answers 2

4

The sizeof operator tells you the size in bytes of the type of its operand. Since strp has type char [6] (i.e. just large enough to store its initiazer since you didn't give an explicit size), it's size is 6. So it's not giving the wrong answer, it's just not telling you what you think it is.

There's a larger problem with this code however, namely you're appending to the string contained in strp but there's no room for any additional characters. As a result, you write past the end of the array, triggering undefined behavior.

The destination of strcat has to have enough room to store the concatenated string. In this case, strp would have to be at least 12 elements long.

2
  1. strcat(strp,strq); invokes undefined bahaviour as strp is not large enough to accommodate the concatenated string. The result of this operation cannot be predicted.

  2. Never ever use sizeof to get string length. sizeof(x) is giving you the size of in bytes x.

Try the same with char strp[100] = "hello";

ALWAYS use strlen

  1. printf("%d", ... (both) invoke undefined behaviour as you use the wrong format. It has to be %zu for type size_t

This program demonstrated the difference between strlen and sizeof:

int main(void) {
    char strq[] = " world";
    char strp[1000] = "hello";

    strcat(strp,strq);
    puts(strp); //hello world
    printf("sizeof(strp) = %zu ",sizeof(strp));
    printf("strlen(strp) = %zu",strlen(strp));
    return 0;
}

result:

hello world
sizeof(strp) = 1000 strlen(strp) = 11

Not the answer you're looking for? Browse other questions tagged or ask your own question.