c - 如何在函数静态中保持值数组?

标签 c arrays function

我在 stackoverflow 上读到,为了使函数中的数组保持静态,我们只需要包含函数 protype/a.k.a global scope?

这里的想法是,一旦用户输入 w、a、s 或 d,方框就会移动,棋盘将使用移动后的方框重新打印。

在这种情况下,电路板生成了一个全新的数字,我怀疑这也是盒子位置没有变化的原因。

我能知道保持静态的正确方法吗?

谢谢

/*Assignment for HIT2080 Intro to Programming */
/*Num-Crash*/
/*Created by: Prince of Potatoes Land*/
/*Date started: Nov 13, 2013*/
/*Date finished: ... , 2013*/

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

#define NROW 19
#define NCOL 19

/*function prototype*/
void WelcomeBoard();        /*Function 1*/
void RandomNum(); /* Keeps the numbers static no matter how many times it is called */
void display_marker( int p , int q , char Array[NROW][NCOL] ); /*This is inside RandomNum Function*/
void MoveNum(  int a, int b, char input );

int main()
{
    /*Function caller*/
    WelcomeBoard();
    RandomNum();

    char input;
    printf("\nw,a,s,d to move");
    input = getch();

    int a = 9;
    int b = 9;

    MoveNum(  a,  b,  input );
    RandomNum();
}

/*function 1*/
void WelcomeBoard()
{
    /*local variable to get the user name*/
    char name[20];

    printf("*****************************WELCOME*****************************\n");
    printf("***************************NUMBER CRASH***************************\n\n");

    printf("Please key in your name: ");
    scanf("%s",&name);
    printf("***Good day %s, let's start a new game... all the best!!!***\n\n",name);
}

/*function 2*/
void RandomNum()
{
    /*Local variable*/
    char Array[NROW][NCOL];
    int x,y,r,c; /*for loop use*/
    int p=9,q=9; /*for indicator used*/

    srand( (unsigned) time(NULL)); /*generate different seed random number everytime*/

    /*assign randon number to odd number in array*/
    for(r=0; r<NROW; r++)
    {
        for(c=0; c<NCOL; c++)
        {
            if (c%2 != 0 && r%2 != 0) /*print number in odd number*/
            {
                do
                {
                    Array[r][c]= rand()%8 +50; /*assign randum number 2 - 9 in array*/

                } while( (Array[r][c] == Array[r+2][c]) && (Array[r][c] == Array[r+4][c] && (Array[r+2][c] == Array[r+4][c])) || (Array[r][c] == Array[r][c+2]) && (Array[r][c] == Array[r][c+4]) && (Array[r][c+2] == Array[r][c+4]));
            }
            /*check either is 3 adjecent when first print*/
            else
            {
            Array[r][c]= ' '; /*for even number to print a space*/
            }
        }
    }

    display_marker( p, q, Array );

    /*print the array*/
    for(x=0; x<NROW; x++)
    {
        for(y=0; y<NCOL; y++)
        {
            printf(" %c ", Array[x][y]);
        }
    printf("\n");
    }
}

/*display_marker function*/
void display_marker( int p, int q, char Array[NROW][NCOL] )
{
    /*assign indicator to cover the middle number*/
    Array[p][q-1] = '|';
    Array[p][q+1] = '|';
    Array[p-1][q] = '-';
    Array[p+1][q] = '-';
}

/*move number function*/
void MoveNum( int p, int q, char userInput )
{
    if ( userInput == 'w' )
        p =- 2;
    else if ( userInput == 'a' )
        q =- 2;
    else if ( userInput == 's' )
        p =+ 2;
    else if ( userInput == 'd' )
        q =+ 2;
    else
        printf("\nwrong Input. Please try again");
}

最佳答案

这里是经过一些修改的程序(有关解释,请参阅答案的末尾)。 我对其进行了测试,它应该可以满足您的要求:

/*Assignment for HIT2080 Intro to Programming */
/*Num-Crash*/
/*Created by: Prince of Potatoes Land*/
/*Date started: Nov 13, 2013*/
/*Date finished: ... , 2013*/

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

#define NROW 19
#define NCOL 19

/*function prototype*/
void WelcomeBoard();        /*Function 1*/
void RandomNum(); /* Keeps the numbers static no matter how many times it is called */
void display_marker(char Array[NROW][NCOL] ); /*This is inside RandomNum Function*/
void MoveNum(char input );
void print_array(char Array[NROW][NCOL]);
void delete_prev_marker(char Array[NROW][NCOL]);

static char Array[NROW][NCOL];
static int a = 9;
static int b = 9;

int main()
{

    /*Function caller*/
    WelcomeBoard();

    RandomNum();
    display_marker(Array );
    print_array(Array);

    char input;
    printf("\nw,a,s,d to move");
    input = getch();

    MoveNum(input );
    display_marker(Array ); 
    print_array(Array);

}


/*function 1*/
void WelcomeBoard()
{
    /*local variable to get the user name*/
    char name[20];

    printf("*****************************WELCOME*****************************\n");
    printf("***************************NUMBER CRASH***************************\n\n");

    printf("Please key in your name: ");
    scanf("%s",&name);
    printf("***Good day %s, let's start a new game... all the best!!!***\n\n",name);
}

/*function 2*/
void RandomNum()
{

    int x,y,r,c; /*for loop use*/

    srand( (unsigned) time(NULL)); /*generate different seed random number everytime*/

    /*assign randon number to odd number in array*/
    for(r=0; r<NROW; r++)
    {
        for(c=0; c<NCOL; c++)
        {
            if (c%2 != 0 && r%2 != 0) /*print number in odd number*/
            {
                do
                {
                    Array[r][c]= rand()%8 +50; /*assign randum number 2 - 9 in array*/

                } while( (Array[r][c] == Array[r+2][c]) && (Array[r][c] == Array[r+4][c] && (Array[r+2][c] == Array[r+4][c])) || (Array[r][c] == Array[r][c+2]) && (Array[r][c] == Array[r][c+4]) && (Array[r][c+2] == Array[r][c+4]));
            }
            /*check either is 3 adjecent when first print*/
            else
            {
            Array[r][c]= ' '; /*for even number to print a space*/
            }
        }
    }

}

/*display_marker function*/
void display_marker(char Array[NROW][NCOL] )
{
    /*assign indicator to cover the middle number*/
    Array[a][b-1] = '|';
    Array[a][b+1] = '|';
    Array[a-1][b] = '-';
    Array[a+1][b] = '-';
}

/*move number function*/
void MoveNum(char userInput )
{
    delete_prev_marker(Array);

    if ( userInput == 'w' )
        a -= 2;
    else if ( userInput == 'a' )
        b -= 2;
    else if ( userInput == 's' )
        a += 2;
    else if ( userInput == 'd' )
        b += 2;
    else
        printf("\nwrong Input. Please try again");
}

void print_array(char Array[NROW][NCOL]){
    int x,y;
    for(x=0; x<NROW; x++)
    {
        for(y=0; y<NCOL; y++)
        {
            printf(" %c ", Array[x][y]);
        }
    printf("\n");
    }
}

void delete_prev_marker(char Array[NROW][NCOL]){
    Array[a][b-1] = ' ';
    Array[a][b+1] = ' ';
    Array[a-1][b] = ' ';
    Array[a+1][b] = ' ';
}


我所做的一些修改包括:
1) 正如您可能已经看到的那样,Array 已被移到带有变量 a 和 b 的 main 之外。我这样做了(可能还有比我的更好的其他实现),因为您希望程序内的所有函数都可以访问数组,并且变量 a 和 b 也可以。 a 和 b 将跟踪标记的位置。我将它们声明为静态的,因为这样 Array、a 和 b 将只能在当前文件中访问。
2) 现在 RandomNum() 只是用随机数填充数组(仅在奇数位置)。这就是它的本意,没有别的。在这个修改之前,你给这个函数太多的事情要做。
3) MoveNum 内部有错误:p =- 2 是错误的。你应该写成 p-=2 或 p=p-2。对于所有用户输入重复此错误。
4) 我已经介绍了几个函数:print_array() 现在是它自己的一个函数(而不是放在 RandomNum 中)。和 delete_prev_marker() 是在将其移动到新位置之前删除前一个标记所必需的。否则你最终会得到两个标记。
5) 最后要说的是,显然所有函数都不需要将a 和b 作为参数,因为现在Array,a 和b 都是全局变量。


重要编辑:快到圣诞节了,所以我决定以优雅的方式(即没有全局变量)实现您的程序。这是代码:

/*Assignment for HIT2080 Intro to Programming */
/*Num-Crash*/
/*Created by: Prince of Potatoes Land*/
/*Date started: Nov 13, 2013*/
/*Date finished: ... , 2013*/

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

#define NROW 19
#define NCOL 19

/*function prototype*/
void WelcomeBoard();        /*Function 1*/
void RandomNum(char Array[NROW][NCOL]); /* Keeps the numbers static no matter how many times it is called */
void display_marker(int *a, int *b, char Array[NROW][NCOL] ); /*This is inside RandomNum Function*/
void MoveNum(char input,int *a, int *b, char Array[NROW][NCOL]);
void print_array(char Array[NROW][NCOL]);
void delete_prev_marker(int *a, int *b, char Array[NROW][NCOL]);

int main()
{
    static int a = 9;
    static int b = 9;
    char Array[NROW][NCOL];

    /*Function caller*/
    WelcomeBoard();

    RandomNum(Array);
    display_marker(&a,&b,Array);
    print_array(Array);

    char input;
    printf("\nw,a,s,d to move");
    input = getch();

    MoveNum(input,&a,&b,Array);
    display_marker(&a,&b,Array); 
    print_array(Array);

}


/*function 1*/
void WelcomeBoard()
{
    /*local variable to get the user name*/
    char name[20];

    printf("*****************************WELCOME*****************************\n");
    printf("***************************NUMBER CRASH***************************\n\n");

    printf("Please key in your name: ");
    scanf("%s",&name);
    printf("***Good day %s, let's start a new game... all the best!!!***\n\n",name);
}

/*function 2*/
void RandomNum(char Array[NROW][NCOL])
{

    int x,y,r,c; /*for loop use*/

    srand( (unsigned) time(NULL)); /*generate different seed random number everytime*/

    /*assign randon number to odd number in array*/
    for(r=0; r<NROW; r++)
    {
        for(c=0; c<NCOL; c++)
        {
            if (c%2 != 0 && r%2 != 0) /*print number in odd number*/
            {
                do
                {
                    Array[r][c]= rand()%8 +50; /*assign randum number 2 - 9 in array*/

                } while( (Array[r][c] == Array[r+2][c]) && (Array[r][c] == Array[r+4][c] && (Array[r+2][c] == Array[r+4][c])) || (Array[r][c] == Array[r][c+2]) && (Array[r][c] == Array[r][c+4]) && (Array[r][c+2] == Array[r][c+4]));
            }
            /*check either is 3 adjecent when first print*/
            else
            {
            Array[r][c]= ' '; /*for even number to print a space*/
            }
        }
    }

}

/*display_marker function*/
void display_marker(int *p, int *q, char Array[NROW][NCOL] )
{
    /*assign indicator to cover the middle number*/
    Array[*p][*q-1] = '|';
    Array[*p][*q+1] = '|';
    Array[*p-1][*q] = '-';
    Array[*p+1][*q] = '-';
}

/*move number function*/
void MoveNum(char userInput, int *p, int *q, char Array[NROW][NCOL])
{
    delete_prev_marker(p,q,Array);

    if ( userInput == 'w' )
        *p -= 2;
    else if ( userInput == 'a' )
        *q -= 2;
    else if ( userInput == 's' )
        *p += 2;
    else if ( userInput == 'd' )
        *q += 2;
    else
        printf("\nwrong Input. Please try again");
}

void print_array(char Array[NROW][NCOL]){
    int x,y;
    for(x=0; x<NROW; x++)
    {
        for(y=0; y<NCOL; y++)
        {
            printf(" %c ", Array[x][y]);
        }
    printf("\n");
    }
}

void delete_prev_marker(int *p, int *q, char Array[NROW][NCOL]){
    Array[*p][*q-1] = ' ';
    Array[*p][*q+1] = ' ';
    Array[*p-1][*q] = ' ';
    Array[*p+1][*q] = ' ';
}


显然代码有一些变化。首先Array,a和b是局部变量。 a 和 b 是静态的,因此它们将保留其值。对于数组,不需要将其声明为静态的,因为当我们调用函数时,指向数组的指针将作为参数传递(数组没有按值传递)。但正如您可能已经看到的那样,一些函数的原型(prototype)现在需要一个指向 a 的指针和一个指向 b 的指针。这是必要的,因为如果我们有整数(而不是指向整数的指针)作为参数或我们的函数,那么这些整数将按值传递并且标记永远不会移动(因为我们会修改 a 的副本和 b 的副本) .所以我们必须使用指针。其余部分与第一个实现几乎相同。

关于c - 如何在函数静态中保持值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043468/

相关文章:

c++ - 使用函数的计算器

c - 用于查询和设置 bios 属性的 API

javascript - 动态添加数组元素到 JSON 对象

php - PHP:检查键值不为空

java - 在 ONE 函数中获取 2D 数组的坐标

javascript - 调用另一个函数时如何禁用该函数?

c - 在其 makefile 中引用 C 代码定义的宏

c - 如何用 ascii 中表示为 int 的值修改 char 指针的内容?

c++ - 使用 LDAP 和 Windows Active Directory 进行用户身份验证 (Windows Server 2016)

java - 打印不重复的字符元素