Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to reset a char[] in C?

I use a string:

char    word[100];

I add some chars to each position starting at 0. But then I need be able to clear all those positions so that I can start add new characters starting at 0.

If I don't do that then if the second string is shorten then the first one I end up having extra characters from the first string when adding the second one since I don't overwrite them.

like image 391
goe Avatar asked Nov 14 '09 23:11

goe


People also ask

What does char [] mean in C?

Updated: 01/31/2019 by Computer Hope. The abbreviation char is used as a reserved keyword in some programming languages, such as C, C++, C#, and Java. It is short for character, which is a data type that holds one character (letter, number, etc.) of data.

How do I empty a char string?

If you want to "empty" it in the sense that when it's printed, nothing will be printed, then yes, just set the first char to `\0'.

How do you delete a char array in C++?

The code: char *p = new char[200]; p[100] = '\0'; delete[] p; is perfectly valid C++.

Can you redefine a string in C?

You need to copy the string into another, not read-only memory buffer and modify it there. Use strncpy() for copying the string, strlen() for detecting string length, malloc() and free() for dynamically allocating a buffer for the new string. Show activity on this post. The malloc needs 1 more byte.


Video Answer


2 Answers

If you want to zero out the whole array, you can:

memset(word, 0, sizeof(word));
like image 74
mmx Avatar answered Sep 22 '22 15:09

mmx


You don't need to clear them if you are using C-style zero-terminated strings. You only need to set the element after the final character in the string to NUL ('\0').

For example,

char buffer[30] = { 'H', 'i', ' ', 'T', 'h', 'e', 'r', 'e', 0 };
// or, similarly:
// char buffer[30] = "Hi There";  // either example will work here.

printf("%s", buffer);
buffer[2] = '\0';
printf("%s", buffer)

will output

Hi There
Hi

even though it is still true that buffer[3] == 'T'.

like image 28
Heath Hunnicutt Avatar answered Sep 25 '22 15:09

Heath Hunnicutt