Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 4 of 4

Thread: Array null termination

  1. #1
    Junior Member
    Join Date
    Oct 2018

    Array null termination

    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]?

    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?

    byte surveyVariables[11]; 
    if (page >= 1) {
     surveyVariables[page - 2] = upDown;  
     surveyVariables[page - 1] = '\0';
    Thank you for your help.

  2. #2
    Senior Member+ defragster's Avatar
    Join Date
    Feb 2015
    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.

  3. #3
    Senior Member+ MichaelMeissner's Avatar
    Join Date
    Nov 2012
    Ayer Massachussetts
    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.

  4. #4
    Junior Member
    Join Date
    Oct 2018
    Thank you for confirming that.

    I really appreciate the wisdom and time that you guys give.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts