Search code examples
cpointersmemorydesktop

Can i use pointer arithmetic with Heap Functions to store arrays?


I'm very new to C and i am trying to understand some notions about memory concepts. I already took a look at basic pointer functionality and wanted to try and make a function that calculates quadratic functions. The problem is that i needed my function to return an array (for result x1 and x2), and since that's not possible in C, i was left with heaps and poiners. I built this code and it works just fine but since C is so complex i wanted a second (or a third, fourth :D) opinion on this, specifically at the HeapAlloc and *result_ptr pointer arithmetic.

Is this correct? Can it cause any problem? Or is this the right way to do it? I honestly dont have any clue, all i know is that it works for now.

#include <stdio.h>
#include <math.h>
#include <heapapi.h>

float * bhaskara_heap(float a, float b, float c, HANDLE SysHeap){ // Returns the pointer for where the result is stored
    float delta = sqrt((b * b) - (4 * (a * c)));

    float divisor = 2 * a;

    float plus_x = ((-1 * b) + delta) / 2;
    float minus_x = ((-1 * b) - delta) / 2;

    /**
     * @brief Here, i use a pre-defined Handle to allocate 8 bytes (2 floats * 4 bytes),
     * then, i fill the address with the first value and the next one (ptr + 1) with the other value
    */
    float *result_ptr = HeapAlloc(SysHeap, HEAP_GENERATE_EXCEPTIONS, 8);

    *result_ptr = plus_x;
    *(result_ptr + 1) = minus_x;
    return result_ptr;
}

int main(int argc, char *argv[]){
    float a = atof(argv[1]);
    float b = atof(argv[2]);
    float c = atof(argv[3]);

    /**
     * @brief Creates a Heap in the virtual memory space,
     * with a min-size of 512 bytes, and dynamic max-size
    */
    HANDLE SysHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 512, 0);

    float *test = bhaskara_heap(a, b, c, SysHeap); // Calculates the quadratic function and store results in the defined memory space

    printf("O endereço de result_ptr é: %x\nE o de result_ptr + 1 é: %x\n", test,(test + 1));
    printf("O valor de result_ptr é: %f\n", *test);

    HeapFree(SysHeap, 0, test); // Here, i free the memory before "displaying" the last result, for test purposes

    printf("O segundo valor de result_ptr é: %f\n", *(test+1));

    HeapDestroy(SysHeap); // Destroys the heap and ends the proccess
    return(0);
}```

Solution

  • The problem is that i needed my function to return an array (for result x1 and x2), and since that's not possible in C

    The solution is to return a struct:

    struct QuadraticSolution {
      _Complex double x1;
      _Complex double x2;
    };
    
    struct QuadraticSolution solveQuadraticEquation(double a, double b, double c) {
      // ... calculate x1 and x2 ... 
      struct QuadraticSolution res = {x1, x2};
      return res;
    }