Search code examples
carraysstringnul

Best practice to declare character array in C


I have to read data from a device which is 4 bytes long so that I have declared array like

char data[4] = {0};

I will parse this as per index and guarantee to stop at index 3.

data[0]..data[3]

In this case there is no room for NUL('\0').

I want to know is this considered safe or I should declare array as

char data[5] = {0};

This array will not be used in str* series of functions.


Solution

  • If the data to be read is a string of 4 bytes or if it is greater than 4 bytes and you are using char as a character array instead of string then no need to worry. Otherwise you have to care about '\0'.