简体   繁体   中英

c memset pointer array

I have a dynamic allocation of my pointer array with a length of 10.

Now I want to initialize this array with all "1".

But if I print out the array[2] it shows me 0. If I print out array[1] it shows me a high number like 4905904374893479. Why is this array not set to "1" on all positions?

I don't have much experience with that but I didn't find a solution.

uint64_t *array=  malloc((10) * sizeof(uint64_t));
memset(array,1, sizeof(*array));
printf("array[2]: %llu \n", primes[2]); 

*array is a single uint64_t , not the entire array. That means your memset is not setting the entire array, just the first element of it.

And, before you decide to use sizeof(array) , be aware that it decays to the pointer to that array so will also not be the correct size.

The memset function works on bytes rather than wider data types so, unless you want every byte set to the same value, memset is not the tool for the job. It works when setting them to 0 simply because that's represented by an all-zero pattern.

Your best bet would be to initialise each explicitly with something like:

uint64_t *array=  malloc(10 * sizeof(uint64_t));
// should really check for malloc failure.
for (size_t idx = 0; idx < 10; idx++)
    array[idx] = 1;

memset fills it with char s, so what you get in each 64-bit entry is 0x0101010101010101 .

And BTW, sizeof(*array) gives you the size of only a single entry in the array.

You may as well use a simple for loop:

for (i=0; i<10; i++)
    array[i] = 1;

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