How to manually add null terminator?

QuestionsQuestions8 SkillsProBuild Functions In CNov, 11 2025
0192

To manually add a null terminator in C or C++, you can simply assign the null character ('\0') to the position in the character array where you want the string to end. This is typically done after you have finished populating the array with characters.

Example:

#include <stdio.h>

int main() {
    char greeting[10]; // Declare an array with enough space

    // Manually populate the array
    greeting[0] = 'H';
    greeting[1] = 'e';
    greeting[2] = 'l';
    greeting[3] = 'l';
    greeting[4] = 'o';

    // Add the null terminator
    greeting[5] = '\0'; // Mark the end of the string

    printf("%s\n", greeting); // Output: Hello
    return 0;
}

Key Points:

  • Ensure that the array has enough space to accommodate the characters plus the null terminator.
  • The null terminator must be placed at the correct index to avoid undefined behavior when using string functions.

If you have further questions about string manipulation or null terminators, feel free to ask!

0 Comments

no data
Be the first to share your comment!