Reputation: 71
If I wanted to translate fill_n
function from CPP to C what would that look like?
If I have two fill_n
function below and I wanted to populate it 0
in C how would I do that?
fill_n(vaToPa, number_of_virtual_memory, 0);
fill_n(paToVa, number_of_physical_memory, 0);
Upvotes: 2
Views: 537
Reputation: 4217
For bytes, you can use memset
. For wchar_t
you can use wmemset
. Apart from that, the standard library doesn't have a generic function for filling. You can make one, but it won't look as clean as templates, so you might want to use a plain for loop in most cases. It would maybe look something like this:
#include <stdio.h>
#include <string.h>
void my_fill_n(void *base, const void *fill, size_t nmemb, size_t size)
{
for (char *i = base; i < (char *)base + nmemb * size; i += size)
memcpy(i, fill, size);
}
int main(void)
{
int a[10];
my_fill_n(a, &(int){42}, sizeof a / sizeof *a, sizeof *a);
for (unsigned i = 0; i < sizeof a / sizeof *a; ++i)
printf("%d\n", a[i]);
}
Output:
42
42
42
42
42
42
42
42
42
42
Note that my_fill_n
is also limited compared to std::fill_n
in that it will only work with arrays, not any other data structures.
Upvotes: 2
Reputation: 238411
Is there an equivalent function for fill_n in C?
No, there is no equivalent function template in C. There are no function templates at all in C.
It is quite simple however and such function can be implemented using a loop.
If I have two fill_n function below and I wanted to populate it 0 in C how would I do that?
fill_n(vaToPa, number_of_virtual_memory, 0); fill_n(paToVa, number_of_physical_memory, 0);
That depends on the types of vaToPa and paToVa. If they're arrays or pointers, then in case of 0, you can use memset:
memset(vaToPa, 0, number_of_virtual_memory * sizeof(*vaToPa));
Upvotes: 0