Array null termination

Status
Not open for further replies.

xenington

Well-known member
Hi All

Apologies for the general nature of this question, but I have only become more confused by what I have read.

There are no problems with the following code (yet), but I was wondering how the following arrays should be null terminated (if it isn't done automatically).

The following array contains 10 constant strings, the longest of which is 24 characters. Is it correct to declare it as [10][25]?

Code:
const char variableNames[10][25] = {"Survey Mode :   ", "Units :   ", "Walking Pace (cm/s) :   ", "Readings per Unit :   ", "Traverses per Metre :   ",
                                     "Linear or Return :   ", "Grid Length :   ", "Grid Width :   ", "Start Corner :   ", "Start Direction :   "};

The next array contains 10 variable unsigned char which are filled as the user makes inputs via questions on 10 different pages. There will always be 10 char. Is it necessary to manually add a null terminator as each char is filled? As per below?

Code:
byte surveyVariables[11]; 

if (page >= 1) {
 surveyVariables[page - 2] = upDown;  
[COLOR="#FF0000"] surveyVariables[page - 1] = '\0';[/COLOR]
}

Thank you for your help.
 
With 24 used characters the compiler requires room to place the NULL terminator, so yes you must ask for [25], asking for any less than that will result in :: "error: initializer-string for array of chars is too long"

C strings are up to the code to assure they are NULL terminated as needed. If a NULL is not properly placed the string will 'continue' through memory until a NULL is found.
 
It is a convention of the C/C++ libraries that strings have a null byte at the end. There are alternate versions of the libraries where you pass in the length, but for the default case, always make sure the array has enough room for the null byte, and store such a null byte when you are building up the string, character by character.
 
Status
Not open for further replies.
Back
Top