睿宏 陳
PRO
last month
睿宏country asked

If I want to take a series of number as input. And I write like this: int numbers[6]; for (int i = 0; i < 5; i++){ scanf("%d", &numbers[i]); } Will this include the null terminator? Or should I add number[i] = '\0' outside the for loop?

Udayan Shakya
Expert
last month
Udayan Shakya answered

Hi again! You don't need null terminators for an array of numbers. You only need to add null terminators at the end of strings.

This is because strings in C are just character arrays. But how do you know if a char array is a string or just an ordinary group of characters?

For example, suppose you have the following arrays:

// not a C string, just a simple char array
char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };

// is a C string because of \0
char greeting1[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };

// also a C string (compiler adds '\0')
char greeting2[] = "Hello";

Basically, normal char arrays don't have \0 at the end, but strings do. The presence of \0 is how C knows whether something is a string or not.

So, you don't need to put \0 in arrays except for strings.

Hope that helps!

C
This question was asked as part of the Learn C Programming course.