我可以将指针算法与堆函数一起使用来存储数组吗?

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

对 C 非常陌生,我正在尝试了解有关内存概念的一些概念。我已经了解了基本的指针功能,并想尝试创建一个计算二次函数的函数。问题是我需要我的函数 return 一个数组(对于结果 x1 和 x2),因为这在 C 中是不可能的,所以我只剩下一堆和指针。我构建了这段代码,它工作得很好,但由于 C 非常复杂,我想对此提出第二个(或第三个、第四个 :D)意见,特别是 HeapAlloc*result_ptr 指针算法。

这是正确的吗?它会引起任何问题吗?或者这是正确的方法吗?老实说,我没有任何线索,我只知道它现在有效。

#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);
}```

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

解决方法是return一个结构:

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;
}