Search code examples
carraysmallocfree

Modulus Division With Arrays in C, Malloc (Free)


Print all the numbers divisible by n in the range [start, end]. Program contains 3 variables, Start, End, and n Using C coding. This is what I have so far, I am not sure how to allocate the memory every time a user enters a new start/end value.

size_t  = end;
    int *a = malloc((max+1) * sizeof *a);
    if (a) {
        for (size_t i = 0; i <= max; i++){
            a[i] = i;
        free(a);
        }
    }
    return 0;

Solution

  • size_t = end;

    This line concerns me. I recommend you, doing this:

    int function(int max){
        int *a = (int*) malloc ( (max+1) * sizeof(int));
        if (a){
            for (int i = 0 ; i<=max ; ++i){
                a[i] = i;
            }
        free(a);
        return (1);
        }
    return (0);
    }
    
    • The function only request the size of the vector, in you case, there is no need for something else, as far as I see.

    • I recommend you having a return to int, so you can check if the allocation was successfully done or not

    • It does not make sense, at least for me, the definition of the size_t. Size_t is a function. Size_t is a function, and, for this reason, it should be called with parenthesis ( ex size_t() ). What goes inside the parenthesis is a type, variable, or something that you want to know the "size of". It is used, in my code as sizeof(int), because you want to know to size of an integer, so you can allocate "integer blocks of memory"

    • Dont forget to cast before the malloc. Malloc has return to a void pointer (void*). This means you need to use this cast (int*) if you are going to point to a integer.

    • I how are you going to call the function, but, you should considerate changing the max+1 to max. For me it makes more logic.