Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a this fragment of code in C++:

char x[50];
cout << x << endl;

which outputs some random symbols as seen here: enter image description here

So my first question: what is the reason behind this output? Shouldn't it be spaces or at least same symbols?

The reason I am concerned with this is that I am writing program in CUDA and I'm doing some character manipulations inside __global__ function, hence the use of string gives a "calling host function is not allowed" error. But if I am using "big enough" char array (each chunk of text I am operating with differs in size, meaning that it will not always utilize char array fully) it's sometimes not fully filled and I left with junk like in the picture below hanging at the end of text:

enter image description here

So my second question: is there any way to avoid this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
984 views
Welcome To Ask or Share your Answers For Others

1 Answer

what is the reason behind this output?

The values in an automatic variable are indeterminate. The standard doesn't specify it, so it might be spaces as you said, it might be random content.

[...] sometimes not fully filled and I left with junk [...]

Strings in C are null-terminated, so any routine dedicated to printing a string will loop as long as no null byte is encountered. In uninitialized memory, this null byte occurs randomly (or not at all). These weird, trailing characters are a result of that.

is there any way to avoid this?

Yes. Initialize it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...