如何返回静态数组指针

编程入门 行业动态 更新时间:2024-10-26 18:16:11
本文介绍了如何返回静态数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

如何返回静态数组指针

本文发布于:2023-07-29 08:37:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239141.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   静态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!