我如何 return 从 C 到 C++ 的 calloc 指针?

How can I return a calloc pointer from C into C++?

我正在从事一个个人项目,该项目要求我从 C++ 代码调用 C 函数。这些 C 函数 return 一个 calloc() 指针。

1t5.h

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

char * prob1(char * number);

1t5.c

#include <1t5.h>

char * prob1(char * number) {
    int ni = atoi(number);
    char prompt[] = "hello\n";
    char * answer = (char*)calloc(ni, sizeof(prompt));
    for (int i = 0; i < ni; i++) {
        strcat(*answer, prompt);
    }
    return answer;
}

该 C 代码应该 return 给定数量的“hello\n”。

linking.cpp

string Link::problemRouting(string problem, vector<string> contents) {
    string answers = "";
    char * ca;

    int pi = stoi(problem);

    for (int i = 0; i < contents.size(); i++) {
        ca = cv.stringToChar(contents[i]);
        // C Standard
        if (pi <= 5) {
            char * answer;
            switch(pi) {
                case 1:{
                    answer = prob1(ca);
                }
                case 2: {
                    answer = prob2(ca);
                }
                case 3: {
                    answer = prob3(ca);
                }
                case 4: {
                    answer = prob4(ca);
                }
                case 5: {
                    answer = prob5(ca);
                }
            }

            cout << answer;
            answers+=answer;
            free(answer);
        }
    }

    return answers;
}

此 C++ 代码采用 return 值并将其保存以稍后存储到文本文件中。

问题是当我输入一个数字时,比方说 257,然后 return 值是 257,而不是一大堆 "hello\n"

感谢@Remy Lebeau 的回答。

我的代码包含很多内存泄漏的机会,导致 return 值一团糟。

string Link::problemRouting(string problem, vector<string> contents) {
string answers = "";
char * ca;

int pi = stoi(problem);

for (int i = 0; i < contents.size(); i++) {
    ca = cv.stringToChar(contents[i]);
    // C Standard
    if (pi <= 5) {
        char * answer;
        switch(pi) {
            case 1:{
                answer = prob1(ca);
                break;
            }
        }
        free(ca);
        cout << answer;
        answers+=answer;
        free(answer);
    }
}

return answers;
}