开发者

How do I clear an array in C?

开发者 https://www.devze.com 2023-01-18 00:55 出处:网络
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(). You cannot assign anything to an array,
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().


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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消