AAAgradebeef
AAAgradebeef

Reputation: 45

How to get char to be null?

So This is what I wrote to test the windows subsystem for ubuntu:

#include <stdio.h>

int () {
     char a = '\0';
     printf("H%cello World\n",a);
     return 0;
}

I compiled it, then ran the program. It shows:

 USER@DESKTOP-blahblah~/dir/%./a.out
 H ello World

????

Screenshot for reference: https://gyazo.com/c25c4214f00e90c8e123f45e84ca1964

EDIT:::

I expected

 USER@DESKTOP-blahblah~/dir/%./a.out
 Hello World

Upvotes: 0

Views: 969

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263177

 char a = '\0';
 printf("H%cello World\n",a);

a is a null character, not an empty character. In fact there's no such thing as an empty character. The printf call will print H, followed by a null character, followed by "ello World", followed by a newline character.

On my system (Ubuntu, xterm), when I run your program (after fixing it) I see:

Hello World

because I happen to be using a terminal emulator that ignores null characters. You apparently are using one that either prints a space or just advances the cursor when you print a null character.

No, there's no value to which you can set a that will cause your program to print just Hello World.

If you wanted to modify your program to use an empty string (which does exist) rather than an empty character (which doesn't), you could:

#include <stdio.h>
int main(void) {
     char empty[] = "";
     printf("H%sello World\n", empty);
}

Upvotes: 3

user2736738
user2736738

Reputation: 30906

There is no empty char as you are thinking. NUL terminating char is not an empty char. It is a character with an ascii code of 0. You have printed the NUL terminating char. And it is not outputting space - it is simply printing the '\0'. It might be something else on different systems.

Upvotes: 1

Related Questions