Search code examples
carraysfunctionmemset

How to initialize arrays in 2 ways using loop and memset?


I am trying to answer a question in my C programming book, but I am not sure if my answer is correct.
The book doesn't provide any answers though. I am new to C programming, and any help will be appreciated.
Question:
Assume you have declared an array as follows:

float data[1000];

Show two ways to initialize all elements of the array to 0.
Use a loop and an assignment statement for one method, and the memset () function for the other.

my current code:

#include <stdio.h>

float data[1000]; 

main(){
    int count;
    for (count = 0; count < 1000; count++){
        scanf("%f", &data[count]);
    }
    for (count = 0; count < 1000; count++){
        printf("Array %i: %f\n", count, data[count]);
    }
}

Solution

  • A few points to help you get started:

    • You're trying to set all items to 0. Scanf requires you to input all values. This isn't necessary as you could just set them to 0 with data[count]=0.0f; inside of that for loop.
    • memset is a function that will do something similar for you (including the for loop). Have a look at the documentation of memset:

    memset

    void * memset ( void * ptr, int value, size_t num );

    Fill block of memory Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

    Parameters

    • ptr: Pointer to the block of memory to fill.
    • value: Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
    • num: Number of bytes to be set to the value. size_t is an unsigned integral type.

    You should notice that memset only works with bytes. So you can use it to set a float to 0, as it consists of 4 bytes that are all 0, but you cannot set it to 1 for instance. But as notices by other users, this just happens to be so on most hardware.