I’m wondering why this code prints a zero.
int x = 10;
char newChar[x];
printf(“%d\n”,strlen(newChar));
I’m wondering why this code prints a zero.
int x = 10;
char newChar[x];
printf(“%d\n”,strlen(newChar));
strlen()
computes the amount of characters in a string. It counts characters up to the null character \0
, which terminates a string. It returns the amount of characters read up to but not including that null character.
In your provided example the char
array newChar
is uninitialized; it has no string in it.
Thus, the output shall be 0
.
The behavior is per standard undefined, when using uninitialized objects. In production code, Always initialize objects or, in the case of VLAs like newChar
is, assign its elements with "placeholder" values or use strcpy
(with VLAS of char
) to copy an empty-string (""
) into it, before using them in any manner.
Technically, it is possible that strlen()
will return a value different than 0
on a different machine or already at a different execution of the program just because the behavior is undefined -> one or more elements could have a non-zero value followed by an element with a 0
value - making the pseudo-string effect perfect.
Maybe you wanted to calculate the number of elements in newChar
.
Therefore, sizeof
instead of strlen()
would be appropriate:
int x = 10;
char newChar[x];
printf("%zu\n", sizeof(newChar) / sizeof(*newChar));
#include <stdio.h>
int main(void)
{
int x = 10;
char newChar[x];
printf("The number of elements in newChar is: %zu\n", sizeof(newChar) / sizeof(*newChar));
}
Output:
The number of elements in newChar is: 10