Search code examples
cdynamic-memory-allocationsizeofpointer-arithmetic

Looping through a double pointer array and multiply or not multiply with sizeof in C?


#include <stdio.h>
#include <stdlib.h>

int main(void) {
    double *array;
    unsigned int size;

    printf("Choose size for your number array: ");
    scanf("%u", &size);

    array = malloc(sizeof(double) * size);

    return 0;
}

I memory allocated sizeof(double) * size, which I don't know if sizeof(double) is necessary, but sizeof(double) is not 1, so I don't know if I should either:

for (int i = 0; i < size; i++) {

} 

For loop through size without multiply it with sizeof(double), or:

for (int i = 0; i < sizeof(double) * size; i++) {

}

For loop and multiply size with sizeof(double) as well? The reason why I'm asking is because I really want to be careful and prevent going over size.

For loop without multiplying sizeof(double) or not?


Solution

  • You allocate sizeof(double) * size memory to have array of doubles, the number of elements is size. So multiply in malloc, don't multiply in for