可以使用switch语句来根据字符串执行不同的函数,具体实现如下:

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

typedef struct {
    char str[20];
} MyStruct;

void func1() {
    printf("This is function 1.\n");
}

void func2() {
    printf("This is function 2.\n");
}

void func3() {
    printf("This is function 3.\n");
}

int main() {
    MyStruct arr[3] = {{"function1"}, {"function2"}, {"function3"}};

    for (int i = 0; i < 3; i++) {
        switch (strcmp(arr[i].str, "function1")) {
            case 0:
                func1();
                break;
            case 1:
                switch (strcmp(arr[i].str, "function2")) {
                    case 0:
                        func2();
                        break;
                    case 1:
                        func3();
                        break;
                }
                break;
        }
    }

    return 0;
}

在上述例子中,我们定义了一个结构体数组arr,包含了三个字符串"function1""function2""function3"。然后我们使用一个for循环遍历数组中的元素,并根据字符串执行不同的函数。使用strcmp函数进行字符串比较,如果相等则执行对应的函数。由于switch语句只能匹配整数类型的值,我们需要先将字符串比较的结果转换成整数类型

C语言有一个结构体数组根据结构体中的字符串执行不同的函数。

原文地址: https://www.cveoy.top/t/topic/hto3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录