c - 如何在 C 中返回静态分配的二维数组?

标签 c multidimensional-array return-type function-declaration

我在 spbox.c 中有以下代码:

#include <stdbool.h>
#include <stdint.h>

typedef struct {
    bool initialized;
    uint32_t Spbox[8][64]; // Combined S and P boxes
} spboxState;

static spboxState stateInstance;

uint32_t ** desGetSpbox(void) {
    if (!(stateInstance.initialized)) {
        // TODO: Compute data to populate Spbox array
        stateInstance.initialized = true;
    }
    return stateInstance.Spbox;
}

我编译它:

clang -c spbox.c

我收到关于不兼容指针返回类型的警告:

spbox.c:16:9: warning: incompatible pointer types returning 'uint32_t [8][64]' from a function with result type 'uint32_t **' (aka 'unsigned int **') [-Wincompatible-pointer-types]
        return stateInstance.Spbox;
               ^~~~~~~~~~~~~~~~~~~
1 warning generated.

如何更改我的代码以使警告消失?这是说 uint32_t **uint32_t [8][64] 不兼容。但是,如果我尝试使后者成为返回类型,则会出现语法错误。

最佳答案

您不能返回数组。但是您可以返回一个指向数组或其第一个元素的指针。

例如

uint32_t ( * desGetSpbox(void) )[8][64] {
    if (!(stateInstance.initialized)) {
        // TODO: Compute data to populate Spbox array
        stateInstance.initialized = true;
    }
    return &stateInstance.Spbox;
}

或者

uint32_t ( * desGetSpbox(void) )[64] {
    if (!(stateInstance.initialized)) {
        // TODO: Compute data to populate Spbox array
        stateInstance.initialized = true;
    }
    return stateInstance.Spbox;
}

这是一个演示程序

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>

enum { M = 8, N = 64 };

typedef struct {
    bool initialized;
    uint32_t Spbox[M][N]; // Combined S and P boxes
} spboxState;

static spboxState stateInstance;

uint32_t ( *desGetSpbox1( void ) )[M][N] 
{
    stateInstance.Spbox[0][0] = 10;
    return &stateInstance.Spbox;
}

uint32_t ( *desGetSpbox2( void ) )[N] 
{
    stateInstance.Spbox[0][0] = 10;
    return stateInstance.Spbox;
}


int main(void) 
{
    uint32_t ( *p1 )[M][N] = desGetSpbox1();
    
    printf( "%" PRIu32 "\n", ( *p1 )[0][0] );

    uint32_t ( *p2 )[N] = desGetSpbox2();
    
    printf( "%" PRIu32 "\n", ( *p2 )[0] );

    return 0;
}

程序输出为

10
10

关于c - 如何在 C 中返回静态分配的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66552942/

相关文章:

algorithm - 确定二维数组中重复值是否存在的最有效方法,像表格一样排列(有一些起始想法)

java - 移动二维数组中的元素

soap - 如何通过 Web 服务发送 ArrayList?

java - uml 类中缺少返回类型

c - 65 是如何翻译成 'A' 字符的?

java - 为什么Android使用Java概念而不是D语言或C或C++?但是 Chromium 网络浏览器是 C++ 的,它的匹配非常复杂

转换和 copy_to_user 宏

c - 删除二进制文件中的条目时出错

c - 如何在内存中连续分配 char 数组的二维数组并在单次调用中写入文件

java - 在 main 函数中一起返回一个数组和一个变量