简体   繁体   中英

Using memset to initialize an integer array

I have a malloc'd array as follows:

int* buf;
buf = (int*)malloc(sizeof(int) * N)

where N is the number of elements in the integer array. I am trying to set all N elements in the array to a specific value, say 4 (so buf = [4, 4, 4, ..., 4]).

For intents and purposes, this is mostly an experiment, and so I am trying to only use memset, without for loops . Is this possible?

With memset, I do:

memset(buf, 4, sizeof(int)*N);

which I assumed places a 4 everywhere in the array in memory, but this doesn't seem to work as expected. Suppose N = 20, then the output is:

[1,6,8,4,3,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,0,0,0,0]

which is not what I expected, but what I do notice is it has set the 4th element (which does correspond to sizeof(int)*N) to 4. I thought memset would set it all to 4, similar to the string case?

Here you have two examples

void memsetint(int *table, const int value, size_t size)
{
    while(size--)
    {
        *table++ = value;
    }
}

#define gmemset(table, value, size) _Generic((&table[0]),   \
    int * : memsetint,                                        \
    double * : memsetdouble) (table, value, size)

void memsetdouble(double *table, const double value, size_t size)
{
    while(size--)
    {
        *table++ = value;
    }
}

int main()
{
    double d[1000];

    gmemset(d, 45.34, 1000);
    printf("%f\n", d[300]);

    return 0;
}

#include <string.h>

void mymemset(void *buff, const void *value, const size_t size, size_t count)
{
    unsigned char *b = buff;
    while(count--)
    {
        memcpy(b, value, size);
        b += size;
    }
}

int main()
{
    int x[1000];
    int value = 5;

    mymemset(x, (int []){10}, sizeof(int), 1000);
    mymemset(x, &value, sizeof(int), 1000);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM