从c中的函数返回整数数组值

时间:2015-03-05 19:10:51

标签: c

我真的在努力完成我的任务。我搜索过互联网和youtube,但我仍然没有更聪明。 该程序总共有5个功能,但我坚持第一个。程序应使用1-D阵列读取用户输入的4位数代码(必须是4位数字)。当我试图从函数返回该代码时,我的问题出现了。我得到的只是第一个号码。我知道你不能从c中的函数返回一个数组,并且你必须使用pass by reference,这是我有问题的地方我不完全理解如何做到这一点。我的代码在下面连同我收到的输出。

在我真正挣扎之前,我会非常感激你能给我的任何帮助。

//program to enter a code and return the code to main

#include <stdio.h>
#include <stdlib.h>
#define CODE 4

//function prototypes
int enter_code(int* code_arr);

main()
{
    int code =0;
    int option;
    int exit1=0;


    do
    {

    //print the menu on screen
    printf("\t \t \t1 - Enter the access code\n");
    printf("\t \t \t2 - Encrypt code and verify\n");
    printf("\t \t \t3 - Exit the program \n");

    scanf("%d",& option);

    switch(option)
    {
        case 1:
            {
                //call enter_code function
                code= enter_code(&code);
                printf("\n The returned code is %d \n",code);

                break;
            }

        case 2:
            {
                break;

            }

        case 3:
                {
                    // prompt user to a key to exit
                    printf("\n You choose to exit the program.\n Press a key to exit\n "); 
                    getchar();
                    exit(0);

                    break;

                } 

        default:
            {
                printf("You must enter a number between 1-5\n");
            }


}

    }//end do()

    while(exit1!=5 & exit1 <6);


}//end main


int enter_code (int* code_arr)
{
    int password[CODE];

    int i;

    printf("Enter your 4 digit code \n");
    for(i=0;i<CODE;i++)
    {
        scanf("%d",&password[i]);
    }

    printf("The code entered is:");
    for(i=0;i<CODE;i++)
    {
        printf("%d",password[i]);
    }

    return(*password); //how do i return the full array

}

1 个答案:

答案 0 :(得分:1)

您的函数可以通过作为参数传递的数组返回代码,并使用函数返回值来指示错误。你也可以将它传递给另一个函数。您的简化代码:

#include <stdio.h>
#include <stdlib.h>

#define CODE 4

int enter_code (int* code_arr)
{
    int i;
    printf("Enter your 4 digit code\n");
    for(i=0;i<CODE;i++)
        if (scanf("%d", &code_arr[i]) != 1)
            return 0;
    return 1;
}

int check_code (int* pass_code, int* user_code)
{
    int i;
    for(i=0;i<CODE;i++)
        if (pass_code[i] != user_code[i])
            return 0;
    return 1;
}

int main(void)
{
    int password[CODE] = {0}, passOK[CODE] = {42,24,0,12345678};
    if (!enter_code(password))
        printf ("Bad password entry\n");
    else {
        if (check_code(passOK, password))
            printf("You unlocked the vault\n");
        else
            printf("You don't know the passcode\n");
    }
    return 0;
}

节目输出:

Enter your 4 digit code
42
24
0
12345678
You unlocked the vault