如何返回静态数组指针

如何返回静态数组指针

本文介绍了如何返回静态数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数使用默认值创建一个二维数组.然后,该函数应返回该静态数组的指针.

I'm trying to create a function that creates a bidimensional array with default values. And then, the function should return the pointer for that static array.

int* novoTabuleiro() {

    static int *novoTabuleiro[LINHAS][COLUNAS];

    //Some changes

    return novoTabuleiro;
}

然后我想做这样的事情:

And then I want to do something like this:

int *tabuleiroJogador = novoTabuleiro();

上面的函数有什么问题.我收到的错误是从不兼容的指针类型返回".谢谢.

What is wrong in the function above. The error I receive is "return from incompatible pointer type". Thanks.

推荐答案

您的注释表明该数组应为整数的二维数组:

Your comments indicate that the array is meant to be a 2-D array of ints:

static int novoTabuleiro[LINHAS][COLUNAS];
return novoTabuleiro;

由于数组指针的衰减,return语句中的表达式 novoTabuleiro 的含义与& novoTabuleiro [0] 相同.

Due to array-pointer decay, the expression novoTabuleiro in the return statement means the same as &novoTabuleiro[0].

novoTabuleiro [0] 的类型为"int的数组[COLUNAS]",即 int [COLUNAS] .因此,指向它的指针是 int(*)[COLUNAS] .

The type of novoTabuleiro[0] is "array [COLUNAS] of int" , i.e. int [COLUNAS]. So a pointer to this is int (*)[COLUNAS].

这意味着您的功能必须是:

That means your function needs to be:

int (*func())[COLUNAS]  {

,调用代码为:

int (*tabuleiroJogador)[COLUNAS] = func();

为函数使用不同的名称要比为函数内的数组名称使用的混淆少.

It would be less confusing to use a different name for the function than you use for the name of the array within the function.

这篇关于如何返回静态数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:49