Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C memset - elegantly add a null terminator

Tags:

c

malloc

memset

I followed How to memset char array with null terminating character? to add a null terminator when using the C memset api.

The code worked; I no longer got odd in-memory chars added to the end of my malloc'd char array, due to the null terminator.

/* memset does not add a null terminator */
static void yd_vanilla_stars(size_t *number_of_chars, char *chars_to_pad)
{
    memset(chars_to_pad, 0, *number_of_chars+1);
    memset(chars_to_pad,'*',*number_of_chars);
}

Is there a more elegant way of achieving the same?

like image 741
rustyMagnet Avatar asked Oct 25 '25 09:10

rustyMagnet


1 Answers

You could simply do this:

memset(chars_to_pad, '*', *number_of_chars);
chars_to_pad[*number_of_chars] = '\0';

Also, why number_of_chars is a pointer?

like image 122
HolyBlackCat Avatar answered Oct 27 '25 23:10

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!