Очистка массива char лучший сценарий — memset или нет?
Я хотел знать, что будет лучше в плане производительности.
- Объявление положительного символа (который будет содержать строки, содержащие перевод строки и символ новой строки) перед входом в бесконечный цикл и последующим использованием memset(buff, 0, 60); или же
- Держать это так, как есть. Влияет ли memset на производительность?
Замечания:
Мое требование заключается в том, что мне нужно иметь char массив полностью очищается при каждом перезапуске цикла.
Решение
«Так оно и есть» не дает массив, полный нулей. Но вам не нужно звонить memset тем не мение. Если вы только использовать buff внутри цикла, я думаю, что лучше держать его в рамках цикла:
Другие решения
memset делает некоторую работу, поэтому она должна «влиять на производительность». Хотя, как правило, он сильно оптимизирован, потому что это обычная операция.
Вы вряд ли найдете более быстрый способ очистки массива из-за этого, и для сравнения код, который вы показали, делает не инициализировать массив вообще.
Для справки, это должно выглядеть примерно так:
Единственное решение, которое может быть быстрее, — это найти способ остановиться в зависимости от обнуления буфера в начале каждой итерации.
Если вы последовательно используете его как строку стиля C:
Это установит только первый байт, но если вы используете его как простую строку в стиле C, это все, что вам когда-либо нужно установить, чтобы сделать строку нулевой длины. Это быстрее, чем любое решение, которое заполняет весь буфер, вероятно, в 7 раз на 64-битной машине.
Clear Char Array in C

This article will explain several methods of how to clear char array in C.
Use the memset Function to Clear Char Array in C
The memset function is generally used to set the memory region with the constant value. The function is part of the standard library and is defined in the <string.h> header file.
memset takes three arguments — the first is the void pointer to the memory region, the second argument is the constant byte value, and the last one denotes the number of bytes to be filled at the given memory address. Note that we can pass 0 integer value to clear the char array.
Alternatively, memset can be called with the specific character as the constant byte argument, which can be useful for initializing every given array element with the same values. In this case, we arbitrarily choose the character zero to fill the array, resulting in a cleared memory region.
Use bzero or explicit_bzero Functions to Clear Char Array in C
bzero is another standard library function to fill the memory area with the zero \0 bytes. It only takes two arguments — the pointer to the memory region and the number of bytes to overwrite. explicit_bzero , on the other hand, is an alternative that guarantees to conduct the write operation regardless of compiler optimizations.
If instructed by the user, the compiler analyzes code for redundant instructions and removes them, and the explicit_bzero function is designed for this specific scenario.
Как очистить массив символов в C?

Программирование и разработка
Массивы символов используются для хранения нескольких символьных элементов в непрерывно выделенной памяти. В нескольких вопросах у нас есть необходимость очистить массив символов, но вы не можете очистить массив символов, установив для отдельных членов какое-то значение, указывающее, что они ничего не содержат. Итак, нам нужны какие-то другие методы для выполнения этой задачи. Давайте проверим несколько методов для выполнения этой задачи.
Методы очистки массива символов в C упомянуты ниже:
- Использование элемента NULL
- Использование strcpy для очистки строки
- Использование memset для очистки
- Очистка динамического массива символов с помощью бесплатного
1. Очистка строки в C с использованием (’/0′)
Элемент ’\0′ в строке или массиве символов используется для идентификации последнего элемента массива символов. Для пустого массива символов первым элементом является элемент ’\0′. Итак, мы можем использовать это свойство строки для очистки массива.
clearing a char array c
I thought by setting the first element to a null would clear the entire contents of a char array.
However, this only sets the first element to null.
rather than use memset , I thought the 2 examples above should clear all the data.
16 Answers 16
It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset is probably the most effective way to achieve this.
On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.
An array in C is just a memory location, so indeed, your my_custom_data[0] = ‘\0’; assignment simply sets the first element to zero and leaves the other elements intact.
If you want to clear all the elements of the array, you’ll have to visit each element. That is what memset is for:
This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:
Why would you think setting a single element would clear the entire array? In C, especially, little ever happens without the programmer explicitly programming it. If you set the first element to zero (or any value), then you have done exactly that, and nothing more.
When initializing you can set an array to zero:
Otherwise, I don’t know any technique other than memset, or something similar.
![]()
Try the following code:
![]()
Why not use memset() ? That’s how to do it.
Setting the first element leaves the rest of the memory untouched, but str functions will treat the data as empty.
Pls find below where I have explained with data in the array after case 1 & case 2.
Though setting first argument to NULL will do the trick, using memset is advisable
![]()
I usually just do like this:
Nope. All you are doing is setting the first value to ‘\0’ or 0.
If you are working with null terminated strings, then in the first example, you’ll get behavior that mimics what you expect, however the memory is still set.
If you want to clear the memory without using memset, use a for loop.
You should use memset. Setting just the first element won’t work, you need to set all elements — if not, how could you set only the first element to 0?
Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you’ll need to use memset.
I thought by setting the first element to a null would clear the entire contents of a char array.
That is not correct as you discovered
However, this only sets the first element to null.
You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.
However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory