以下是一个根据 CPU 个数动态生成大小为 3 的二维字符串数组的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysinfo.h>

int main() {
    int cpu_count = get_nprocs();  // 获取 CPU 个数
    char** arr = (char**)malloc(cpu_count * sizeof(char*));  // 分配一维数组
    for (int i = 0; i < cpu_count; i++) {
        arr[i] = (char*)malloc(3 * sizeof(char));  // 分配二维数组的每一行
        strcpy(arr[i], "abc");  // 将字符串赋值给每一行
    }

    // 打印二维数组
    for (int i = 0; i < cpu_count; i++) {
        printf("%s\n", arr[i]);
    }

    // 释放内存
    for (int i = 0; i < cpu_count; i++) {
        free(arr[i]);
    }
    free(arr);

    return 0;
}

该代码使用了 get_nprocs() 函数获取 CPU 个数,然后动态分配了一个大小为 cpu_count 的一维指针数组 arr。接着,使用循环为每一行分配了大小为 3 的字符数组,并将字符串 "abc" 赋值给每一行。最后,通过循环打印二维数组,并释放内存。

请注意,该代码仅是一个示例,实际应用中可能需要根据具体需求进行适当修改


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

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