-1

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]); 
2
  • I think this happens because you try to assign normal integers to an array of 64 bit integers Commented Oct 29, 2016 at 9:18
  • Its not clear what you are trying to do. You assign make array of 10 64bit integers. Then you set the first one to 0x01010101010101 (‭72340172838076673‬), the other 9 you don't set at all and their values will be random. Commented Oct 29, 2016 at 9:19

2 Answers 2

4

*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;
Sign up to request clarification or add additional context in comments.

Comments

3

memset fills it with chars, 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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.