C 语言不支持像 Python 或 JavaScript 那样直接返回多个值,但可以使用指针、结构体、全局变量、数组等方法来实现。在使用指针时,请确保指针指向有效的内存地址。在使用数组时,要小心数组的生命周期。结构体是返回多个不同类型值的最佳选择。

1、使用指针返回多个值

通过传递指针参数,函数可以修改调用者传入的变量。

#include <stdio.h>

void divide(int a, int b, int *quotient, int *remainder) {
    *quotient = a / b;
    *remainder = a % b;
}

int main() {
    int q, r;
    divide(10, 3, &q, &r);
    printf("商: %d, 余数: %d\n", q, r);
    return 0;
}

2、使用 struct 结构体返回多个值

如果需要返回多个不同类型的数据,可以使用结构体。

#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

Point getPoint() {
    Point p = {10, 20};  // 赋值
    return p;
}

int main() {
    Point p = getPoint();
    printf("Point: (%d, %d)\n", p.x, p.y);
    return 0;
}

3、使用 struct + 指针(更高效)

避免结构体拷贝,用指针修改外部变量

#include <stdio.h>

typedef struct {
    int width;
    int height;
} Rectangle;

void getRectangle(Rectangle *r) {
    r->width = 10;
    r->height = 5;
}

int main() {
    Rectangle rect;
    getRectangle(&rect);
    printf("Rectangle: %d x %d\n", rect.width, rect.height);
    return 0;
}

4、使用 malloc() 分配动态结构体

动态分配结构体可用于跨函数返回多个值

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

typedef struct {
    int width;
    int height;
} Rectangle;

Rectangle* createRectangle(int w, int h) {
    Rectangle *r = (Rectangle *)malloc(sizeof(Rectangle));
    if (r) {
        r->width = w;
        r->height = h;
    }
    return r;
}

int main() {
    Rectangle *rect = createRectangle(10, 5);
    if (rect) {
        printf("Rectangle: %d x %d\n", rect->width, rect->height);
        free(rect);  // 释放内存
    }
    return 0;
}

5、使用数组返回多个值

数组适用于相同类型的多个值

#include <stdio.h>

void findFactors(int num, int factors[], int *count) {
    *count = 0;
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            factors[(*count)++] = i;
        }
    }
}

int main() {
    int factors[10];
    int count;
    findFactors(12, factors, &count);

    printf("因数: ");
    for (int i = 0; i < count; i++) {
        printf("%d ", factors[i]);
    }
    printf("\n");

    return 0;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表