为什么未初始化的字符数组被填充随机符号? [英] Why uninitialized char array is filled with random symbols?

查看:490
本文介绍了为什么未初始化的字符数组被填充随机符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C ++ 中有一段代码:

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

输出一些随机符号,如下所示:



所以我的第一个问题:这个输出背后的原因是什么?不应该是空格或至少是相同的符号?



我关心的原因是我正在CUDA编写程序,我正在做一些字符操作 __ global __ 函数中,因此使用 string 给出调用主机函数不允许的错误。
但是如果我使用足够大的字符数组(每个大块的文本,我操作不同的大小,意味着它不会总是充分利用字符数组)它有时不完全填充,我离开了垃圾喜欢在下面的图片中结束文字:





所以我的第二个问题:有什么办法避免这种情况吗?

解决方案


此输出背后的原因是什么?


自动变量中的值为不确定。标准没有指定它,所以它可能是你说的空格,它可能是随机内容。


[...]有时没有完全填充,我离开了垃圾[...]


C中的字符串是空值终止的,打印字符串将循环,只要没有遇到空字节。在未初始化的内存中,这个空字节是随机出现的(或根本不出现)。

有什么方法可以避免这种情况吗?

p>

是的。初始化它。


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

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

which outputs some random symbols as seen 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:

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

解决方案

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.

这篇关于为什么未初始化的字符数组被填充随机符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆