gpt4 book ai didi

c - 如何在 C 语言中将函数的返回值存储在变量中

转载 作者:行者123 更新时间:2023-11-30 20:52:07 25 4
gpt4 key购买 nike

我编写了一个 C 程序如下:-

#include <stdio.h>
#include <conio.h>
#include <string.h>
char getPositions(int randNo, int guessNo);

void main()
{
char positions[6];
clrscr();
positions = getPositions(5242, 5243);
printf(positions);
getchar();

}
char getPositions(int randNo, int guessNo)
{
char outPut[6];
int randNoArr[4], guessNoArr[4];
int c, w, p;

for(int i=4; i>0; i--){
randNoArr[i] = randNo%10;
randNo /= 10;

guessNoArr[i] = guessNo%10;
guessNo /= 10;
//If Number Possitioned Right Place Incress variable c
if(randNoArr[i] == guessNoArr[i]){
c++;
}
}
for(int j=1; j<=4; j++){
if(guessNoArr[j] != randNoArr[1] && guessNoArr[j] != randNoArr[2] && guessNoArr[j] && randNoArr[3] || guessNoArr[j] && randNoArr[4]){
w++;
}
}
if(guessNoArr[1] == randNoArr[2] || guessNoArr[1] == randNoArr[3] || guessNoArr[1] == randNoArr[4]){
p++;
}
if(guessNoArr[2] == randNoArr[1] || guessNoArr[2] == randNoArr[3] || guessNoArr[2] == randNoArr[4]){
p++;
}
if(guessNoArr[3] == randNoArr[1] || guessNoArr[3] == randNoArr[2] || guessNoArr[3] == randNoArr[4]){
p++;
}
if(guessNoArr[4] == randNoArr[1] || guessNoArr[2] == randNoArr[2] || guessNoArr[2] == randNoArr[3]){
p++;
}
sprintf(outPut, "%dC%dW%dP", c,w,p);
return outPut;
}

我有两个错误:

Error prog1.CPP 10: Lvalue required //positions = getPositions(5242, 5243);
Error prog1.cpp 50: Cannot convert 'char *' to 'char' //return outPut;

最佳答案

首先你犯了一个非常可怕的错误:

尝试将函数中本地声明的数组返回到另一个函数。返回数组的正确做法是返回指向它的指针。并确保指针指向您拥有的内存。当函数返回时,局部变量将失去焦点,因此当函数返回时,您不拥有它们。

为您提供快速解决方案:将位置数组作为第三个参数传递并使函数返回 void 现在对您来说是最简单的事情。

关于c - 如何在 C 语言中将函数的返回值存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382533/

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