Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is "{0}" in C?

Tags:

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;
}
like image 233
wizztjh Avatar asked Aug 15 '11 11:08

wizztjh


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.

like image 186
Oliver Charlesworth Avatar answered Sep 23 '22 07:09

Oliver Charlesworth


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.

like image 21
Federico klez Culloca Avatar answered Sep 21 '22 07:09

Federico klez Culloca