如何清除C中的数组? [英] How do I clear an array in C?

查看:24
本文介绍了如何清除C中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char x [1000];
x = 'hello';

我将使用什么来清除 x 的内容?我无法重新初始化它,请使用 strcpy(x, '/0')free().

What would I use to clear the contents of x? I'm not able to re-initialise it, use strcpy(x, '/0') or free().

推荐答案

你不能给数组赋值,你的变量 x 就是这个数组.因此,任何以 x = 开头的都是错误的.其次 'hello' 不是一个字符串,它是一个 int 类型的多字符文字,所以这也没有意义.字符串文字由 " 包围,而字符(或多字符)文字由 ' 包围.

You cannot assign anything to an array, which your variable x is. So therefore anything that starts with x = is wrong. Secondly 'hello' is not a string, it is a multicharacter literal which is of type int, so this doesn’t make sense either. A string literal is enclosed by " while character (or multicharacter) literals are enclosed by '.

因此,如果您想用字符串hello"填充缓冲区 x,请使用 strncpy 或更好的 strlcpy(如果可用):

So if you want to fill your buffer x with the string "hello" you use strncpy or even better strlcpy if available:

 strncpy( x, "hello", sizeof( x ) );
 strlcpy( x, "hello", sizeof( x ) );

strlcpy 函数更好,因为它总是用 nul 字符终止字符串.

The strlcpy function is better because it always terminates the string with a nul character.

如果你想清除它,你可以按照其他答案的建议去做.我建议使用带有空字符串的 strncpystrlcpy ,如@codacci 建议的那样.那是最明显地说嘿,我想清除那个字符串"的代码.如果你想从内存中删除字符串的全部内容(例如,如果它包含密码或类似的东西)使用 memset 作为 @Ken 和 @Tom 建议.

If you want to clear it you could do what the other answers suggested. I’d suggest using strncpy or strlcpy with an empty string as @codaddict suggested. That is the code that says most obviously "hey, I want to clear that string". If you want to remove the whole contents of the string from memory (for example if it contained a password or something like this) use memset as @Ken and @Tom suggested.

另请注意,您从不使用诸如 strcpystrcat 之类的函数,它们不接受输出缓冲区的大小作为参数.这些确实不安全,会导致令人讨厌的错误和安全漏洞.如果你知道不会出错,甚至不要使用它们,养成使用安全功能的习惯.

Also note that you never ever use functions like strcpy or strcat that don’t accept the size of the output buffer as a parameter. These are really not secure and cause nasty bugs and security vulnerabilities. Don’t even use them if you know that nothing can go wrong, just make a habit of using the secure functions.

这篇关于如何清除C中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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