Consider that an application written in C should do 0 to one million calculations. For each calculation, an integer is converted to a string. The problem is that, the digits of integers are uncertain, it can be a 1 digital number to a 10 digital number. So we have to calculate the length of an integer up to one million times and allocate one million times by using dynamic allocation char* string = malloc(sizeof(char) * length_of_integer 1)
. What if we use char string[10]
to avoid allocations, in this way, we have to do padding when converting an uncertain digital number to a string.
My first thought is that, we still calculate the digit of an integer, initialize a string, padding with "0"s according to the result of digit calculation, then use sprintf
for copying the integer to string. But in this way, it still needs up to million calculations for digits of integers. So I would like to ask if there is already any other functions that do the padding? Or is there any other efficient way to reach my goal? Thanks a lot!
CodePudding user response:
Bulk set array values in memory range with memset
void *memset(void *s, int c, size_t n);
The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c. (Documentation)
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int item_count = 25;
int memory_amount = item_count * sizeof(char);
char *pointer = malloc(memory_amount);
memset(pointer, '0', memory_amount);
printf("%s\n", pointer);
free(pointer);
return 0;
}
Output
$ ./a.out
0000000000000000000000000
CodePudding user response:
You don't need padding. All you need is null terminator, and sprintf
already does that.
All string-handling functions ignore everything after terminator.
This is C - nobody cares about contents of a buffer until you explicitly order to read from it.
If your functions are non-compliant, then zero entire buffer before writing to it.
/edit
On a second thought, your functions cannot be non-compliant. If your solution works with malloc
, then the functions in question already don't read past the null terminator. Because with dynamically-allocated memory, there is still junk after null-terminator and to make things worse, it's possibly someone else's junk, so reading it is UB that could end in crash. So you really don't need padding.