[英]Assign function return to char array variable
I have a function called "retornaMaior"
which returns a char array
, and I want to assign this return to a new variable like: 我有一个称为"retornaMaior"
的函数,该函数返回一个char array
,我想将此返回值分配给一个新变量,例如:
char variable[] = retornaMaior();
Is there any way to do this? 有什么办法吗? If there is, how can I do that? 如果有,我该怎么办?
I was thinking about declaring the "variable" as a global like "cartas_jogo" but I don't know if it's right. 我当时正在考虑将“变量”声明为像“ cartas_jogo”这样的全局变量,但我不知道是否正确。
Code below: 代码如下:
char cartas_jogo[] = "4567QJKA23";
char naipes_jogo[] = "ZCEO";
char carta_retorno[2];
int retornaIndice(char carta)
{
int a = 0;
int retorno = 0;
for (a=0; a<strlen(cartas_jogo); a++)
{
if (carta==cartas_jogo[a])
{
retorno = a;
}
}
return retorno;
}
char *retornaMaior(char *cartas, const char carta_comp)
{
int posCartaComp = retornaIndice(carta_comp);
int a = 0;
int posMaior = 0;
int tem = 0;
int posA = 0;
for (a=0; a<6; a+=2)
{
int posCarta = retornaIndice(cartas[a]);
if (tem == 0)
{
if (posCarta>posCartaComp)
{
posMaior = posCarta;
posA = a;
tem = 1;
}
}
else
{
if (posCarta<posMaior)
{
if (posCarta>posCartaComp)
{
posMaior = posCarta;
posA = a;
}
}
}
}
carta_retorno[0] = cartas_jogo[posMaior];
posA++;
carta_retorno[1] = cartas[posA];
if (tem==0)
{
carta_retorno[0] = '0';
carta_retorno[1] = '0';
}
return carta_retorno;
}
char variable[] = retornaMaior();
Probably won't work. 可能行不通。 Instead: 代替:
char *variable = retornaMaior();
Which can still be addressed as an array: 仍然可以将其视为数组:
printf("%c\n", variable[1]);
Within the 'retornaMaior()' function, you will need to put the value returned into memory that can be returned. 在“ retornaMaior()”函数中,您需要将返回的值放入可以返回的内存中。 Using the global variable 'carta_retorno' will probably work; 使用全局变量“ carta_retorno”可能会起作用。 but there is a better way. 但是有更好的方法。
Another option would be to allocate some 'heap' memory to the return value. 另一种选择是为返回值分配一些“堆”内存。 To do this, move 'carta_retorno' from global storage, and move it inside the 'retornaMaior()' function: 为此,请将“ carta_retorno”从全局存储中移出,然后将其移入“ retornaMaior()”函数中:
char carta_retorno[2]; // ---
char *retornaMaior(char *cartas, const char carta_comp)
{
int posCartaComp = retornaIndice(carta_comp);
int a = 0;
int posMaior = 0;
int tem = 0;
int posA = 0;
char *carta_retorno = malloc(2); // +++
As indicated by 'staticx', it is important to ensure that malloc() succeeded: 如“ staticx”所示,确保malloc()成功是很重要的:
if(NULL == carta_retorno)
...
Now, the 'retornaMaior()' function will return the result in allocated memory (rather than using global storage). 现在,“ retornaMaior()”函数将在分配的内存中返回结果(而不是使用全局存储)。
Don't forget that the caller to 'cp=retornaMaior()' needs to call 'free(cp)' when the return value is no longer needed. 不要忘记,当不再需要返回值时,“ cp = retornaMaior()”的调用者需要调用“ free(cp)”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.