what is "{0}" in C?

What does char buf[MAXDATASIZE] = { 0 };'s {0} means?

tried to print it out but it print nothing.

#include <stdio.h>
int main(void)
{ char buf[100] = { 0 }; printf("%s",buf); return 0;
}
1

2 Answers

This is just an initializer list for an array. So it's very like the normal syntax:

char buf[5] = { 1, 2, 3, 4, 5 };

However, the C standard states that if you don't provide enough elements in your initializer list, it will default-initialize the rest of them. So in your code, all elements of buf will end up initialized to 0.

printf doesn't display anything because buf is effectively a zero-length string.

2

You are assigning an array to the buffer.

In the particular case of string, usually, the character whose ASCII value is 0 terminates the string.

For example, if you wanted to put a string that reads 'Hello world' inside the string you could have done

char buf[100] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', 0};

or

char buf[100] = "Hello world";

Anyway, your code prints nothing because you are trying to print a string with length zero, that is an empty string.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like