无法在 C 中返回正确的变量

标签 c

我想尝试使用 C 编写 Kadane 算法。我不仅想返回最大子数组值,还想返回开始和结束索引。

这是代码:

#include <limits.h>
#include <stdio.h>

int kadane(int A[], int size){
    int current_max = INT_MIN;
    int global_max = INT_MIN;
    int start, last;

    for (int i = 0; i <= size; i++){
        if (A[i] > A[i] + current_max){
            current_max = A[i];
            start = i;
        } else {
            current_max += A[i];
        };

        if (current_max >= global_max){
            global_max = current_max;
            last = i;
        };
    };
    return (start, last ,global_max);
}

int main(){
    int sum, size, start, last;
    int A[] = {3,-4,5,1,9,-10,11,2,5,-1,2};
    size = sizeof(A)/sizeof(A[0]);

    start, last, sum = kadane(A, size-1);
    printf("start at %d ; end at %d; sum : %d\n", start, last, sum);
    return 0;
}

虽然最大和的答案是正确的,但是start和last的值确实很奇怪。我使用 printf 检查 kadane 函数的 for 循环中 start 和 last 的值,看起来工作正常。所以我认为问题可能与我返回变量的方式有关。

所以我修改了代码的某些部分,如下所示:

int kadane(int A[], int size){
    ......
    ......
    return (&start, &last ,global_max);
}

然后使用指针来存储它们:

int main(){
    .......
    .......
    int *start;
    int *last;

    *start, *last, sum = kadane(A, size-1);
    printf("start at %d ; end at %d; sum : %d\n", *start, *last, sum);
    return 0;
} 

然后我收到“Segmentation Failure 11”错误。

我尝试理解和搜索我在这里做错了什么,但我找不到它。唯一有效的解决方案是将变量 start 和 last 存储在全局中,以便我可以在任何地方调用 then 而无需返回。但我觉得这不是一个合适的解决方案。有人可以帮我吗?

最佳答案

您有两种解决方案:

1:返回一个包含您需要的所有类型的结构。

struct data {
    int start;
    int last;
    int global_max;
};
struct data kadane(int A[], int size){
    stuct data test = { 1, 1, 1 };
    ......
    ......
    return test;
}

void main() {
    ......
    struct data t = kadane(A, ize);
}

2:使用指针传递值。

void kadane(int A[], int size, int *start, int *last, int *global_max) {
    ......
    ......
    *start = 1;
    *last= 1;
    *global_max= 1;
}

void main() {
    ......
    int a, b, c;
    kadane(A, size, &a, &b, &c);
}

From How do I return multiple values from a function in C?

关于无法在 C 中返回正确的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889157/

相关文章:

c - 无法理解 Malloc 输出

c - 将各种txt文件读入c编程,将其保存到数组中并得出结论: Homework

c - 如何使用 strtok 通过两个分隔符分隔特定字符串到数组

python - Python 中的希尔伯特变换?

c - free() 在 c 代码中收集垃圾值,即使在释放后将指针设置为 NULL,代码也不起作用

c - C中的面向对象编程

c++ - 字符串缓冲区如何导致恶意代码运行?

c - pthread_join 中的段错误

在 "could not access file $libdir/..."中为 Postgres 11 结果创建扩展

c - VS2019 linux头文件