Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() showing different output

Here is a snippet of C99 code:

int main(void)
{
    char c[] = "\0";
    printf("%d %d\n", sizeof(c), strlen(c));

    return 0;
}

The program is outputting 2 0. I do not understand why sizeof(c) implies 2 seeing as I defined c to be a string literal that is immediately NULL terminated. Can someone explain why this is the case? Can you also provide a (some) resource(s) where I can investigate this phenomenon further on my own time.

like image 721
avinashse Avatar asked Aug 14 '13 07:08

avinashse


People also ask

What does sizeof () return in C?

It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

Why is sizeof void 1?

When you do pointer arithmetic adding or removing one unit means adding or removing the object pointed to size. Thus defining sizeof(void) as 1 helps defining void* as a pointer to byte (untyped memory address).

What is sizeof () in C with example?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.

Does sizeof return size of array?

The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100. The B object is simply a pointer.


2 Answers

didn't understand why size of is showing 2.

A string literal has an implicit terminating null character, so the ch[] is actually \0\0, so the size is two. From section 6.4.5 String literals of the C99 standard (draft n1124), clause 5:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals

As for strlen(), it stops counting when it encounters the first null terminating character. The value returned is unrelated to the sizeof the array that is containing the string. In the case of ch[], zero will be returned as the first character in the array is a null terminator.

like image 86
hmjd Avatar answered Sep 30 '22 03:09

hmjd


In C, "" means: give me a string and null terminate it for me.

For example arr[] = "A" is completely equivalent to arr[] = {'A', '\0'};

Thus "\0" means: give me a string containing a null termination, then null terminate it for me.

arr [] = "\0"" is equivalent to arr[] = {'\0', '\0'};

like image 25
Lundin Avatar answered Sep 30 '22 03:09

Lundin