-1

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?

TimelordViktorious
  • 336
  • 3
  • 10
  • 20
  • 2
    `memset` sets bytes, not `int`s, even though the prototype shows the second parameter as type `int`. Read the `man` pages for `memset` again. – cdarke Jan 17 '19 at 22:47
  • 1
    Possible duplicate of [Using memset for integer array in c](https://stackoverflow.com/questions/17288859/using-memset-for-integer-array-in-c) – Blastfurnace Jan 17 '19 at 22:49
  • 1
    Can you give a minimum working example? As indicated above, memset fills all the byte in memory with the same char and cannot be used to initiliaze ints. But your results are somehow weird. – Alain Merigot Jan 17 '19 at 22:50
  • 1
    Output of `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` makes little sense. Post an [mcve] – chux - Reinstate Monica Jan 18 '19 at 03:21

1 Answers1

-1

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74