How do I clear an array in C?

谁说胖子不能爱 提交于 2020-05-29 06:49:31

问题


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

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


回答1:


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 '.

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 ) );

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

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.

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.




回答2:


Usage of free() would be wrong, since x is in the stack.

What do you mean by clear? Set it to a default value? Can you use memset? (I'm copying your code as it is)

#define CLEAR(x) memset(x,'\0',1000)

char x[1000];

x= 'hello';

CLEAR(x)

If not, you can always use a for loop.




回答3:


x='hello';

may not be doing what you expect because ' denotes a character constant (or in this case a multi-character constant) not a string.

In fact, gcc won't accept the above code, complaining that 'hello' is to long (that's on a machine with 4 byte ints), and that x = 'hell' is an incompatible assignment because a char[] is not the same as an int.

Nor should

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

work because you can't assign arrays that way.




回答4:


If by "clear" you mean "clear all bits in the array", how about memset(x, '\0', 1000);?




回答5:


To clear it, you would just reset it all to zero with memset().

char x[1000];
//...
memset(x, 0, sizeof (x));


来源:https://stackoverflow.com/questions/3831191/how-do-i-clear-an-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!