I am currently learning C and I wrote this program to check if the '\0' char is really at the end of strings, as pointed in "K and R".
I had the strangest result though.
If I comment the "int lista[] = {0, 1, 2, 3, 4};" statement out of the program (this is a statement that has nothing to do with the other statements of this program, it was part of another test I was going to make). the output of the program comes out how expected, detecting one '\0' char ending the string. However, if I leave the statement uncommented, the program output detects two '\0' chars at the end of the string. Why does this happens?
This is the program with the statement uncommented:
#include <stdio.h>
int main(void)
{
int lista[] = {0, 1, 2, 3, 4};
char string[] = "linhas";
for (int i = 0; i <= sizeof(string); i++)
{
if (string[i] != '\0')
{
printf("%c\n", string[i]);
}
else
{
printf("this dawmn null char\n");
}
}
}
This outputs:
l
i
n
h
a
s
this dawmn null char
this dawmn null char
this is the program with the line commented out:
#include <stdio.h>
int main(void)
{
/*int lista[] = {0, 1, 2, 3, 4};*/
char string[] = "linhas";
for (int i = 0; i <= sizeof(string); i++)
{
if (string[i] != '\0')
{
printf("%c\n", string[i]);
}
else
{
printf("this dawmn null char\n");
}
}
}
it outputs:
l
i
n
h
a
s
this dawmn null char