gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:03:37 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com