【问题标题】:Making a variable accessible by other functions in C使 C 中的其他函数可以访问变量
【发布时间】:2017-06-09 04:33:47
【问题描述】:

我是编程新手,我们刚刚在课堂上学习了数组。
我们的任务是创建一个不使用全局变量的 C 程序。

我创建了两个函数,一个用于输入数据,一个用于操作(包含一个菜单)。让用户在操作菜单中选择想要进行的操作后,会显示结果并返回菜单。

由于不允许使用全局变量,我无法弄清楚如何使操作函数可以读取某些变量。

void matrix(){
int a, b, c, d, k, m, n, p, q, s=0, first[MAX][MAX], second[MAX][MAX], msum[MAX][MAX], firstt[MAX][MAX], secondt[MAX][MAX], prod[MAX][MAX];
system("CLS");
printf("/-----------------------------------------------------------------------------/\n"
       "\t\t\t\tMatrix\n"
       "/-----------------------------------------------------------------------------/\n");
printf("This program will multiply matrices (up to 3x3 matrix only).\n"
       "Please enter the number of rows of the first matrix: ");
scanf("%d", &m);
if(m>3){
    matrixerror();
}
printf("Please enter then number of columns of the first matrix: ");
scanf("%d", &n);
if(n>3){
    matrixerror();
}
printf("Please enter the number of rows of the second matrix: ");//Matrix 2
scanf("%d", &p);
if(p>3){
    matrixerror();
}
printf("Please enter then number of columns of the second matrix: ");
scanf("%d", &q);
if(q>3){
    matrixerror();
}
printf("\nPlease enter the elements of the first matrix:\n");
for(c=0; c<m; ++c)
    for(d=0; d<n; ++d){
        printf("Enter element a%d%d: ",c+1, d+1);
        scanf("%d", &first[c][d]);
    }
printf("\nPlease enter the elements of the second matrix:\n");   
for(c=0; c<p; ++c)
    for(d=0; d<q; ++d){
        printf("Enter element b%d%d: ",c+1, d+1);   
        scanf("%d", &second[c][d]);
    }

matrixmenu();
}

另一个用于操作

void matrixmenu(){
system("CLS");
char choice;
printf("/-----------------------------------------------------------------------------/\n"
       "\t\t\t\tMatrix\n"
       "/-----------------------------------------------------------------------------/\n");

printf("\n"
       "\t1.  Add Matrices\n"
       "\t2.  Multiply Matrices\n"
       "\t3.  Transpose \n"
       "\tB.  Back \n");
printf("\n\tFirst matrix is : \n\t");
for(a=0; a<m; ++a)
    for(b=0; b<n; ++b){
        printf("%d  ", first[a][b]);
        if (b == n-1)
        printf("\n\n\t");
    }
printf("\n\tSecond matrix is : \n\t");
for(a=0; a<m; ++a)
    for(b=0; b<n; ++b){
        printf("%d  ", second[a][b]);
        if (b == n-1)
        printf("\n\n\t");
    }      
printf("\n");   
printf("/------------------------------------------------------------------------------/ ");
scanf("%s", &choice);
switch(choice){
    case '1':
        printf("\n\tThe sum of entered matrices is: \n\t");

        for (a = 0; a < m; a++){
            for (b = 0 ; b < n; b++){
                msum[a][b] = first[a][b] + second[a][b];
                printf("%d\t", msum[a][b]);
            }
            printf("\n\t");
        }
        printf("\n\t");
        system("PAUSE");
        matrixmenu();
        break;
    case '2':
        if (n != p){
            printf("\n\tError! Matrix cannot be multiplied!\n\t");
            system("PAUSE");
            matrixmenu();
        }
        for (c = 0; c < m; c++){
            for (d = 0; d < q; d++){
                for (k = 0; k < p; k++){
                    s = s + first[c][k]*second[k][d];
                }
            prod[c][d] = s;
            s = 0;
            }
        }
        printf("\n\tThe product matrix is:\n\t");
        for (c = 0; c < m; c++){
            for (d = 0; d < q; d++){
                printf("%d\t", prod[c][d]);
            }
            printf("\n\t");
        }   
        printf("\n\t");
        system("PAUSE");
        matrixmenu();
        break;
    case '3':
        for(a=0; a<m; ++a)//Tranposition
            for(b=0; b<n; ++b)
                firstt[b][a] = first[a][b];
        printf("\n\tThe transpose of the first matrix is:\n\t");
        for(a=0; a<n; ++a)
            for(b=0; b<m; ++b){
                printf("%d  ",firstt[a][b]);
            if(b==m-1)
            used    printf("\n\n\t");
        }
        for(a=0; a<p; ++a)//Tranposition
            for(b=0; b<q; ++b)
                secondt[b][a] = second[a][b];
        printf("\n\tThe transpose of the second matrix is:\n\t");
        for(a=0; a<n; ++a)
            for(b=0; b<m; ++b){
                printf("%d  ",secondt[a][b]);
            if(b==m-1)
                printf("\n\n\t");
            }   
        printf("\n\t");
        system("PAUSE");
        matrixmenu();
        break;
    case 'B':
    case 'b':
        mainmenu();
        break;
    default:
        matrixmenu();
        break;
}
}

【问题讨论】:

  • 将他们的地址传递给您调用的函数。然后它可以引用它们。
  • 并考虑在您的代码中添加一些空白行。你会发现阅读一本没有段落的书就像大多数人(包括你自己在内)会找到你的代码一样困难。
  • 你是怎么做到的?
  • @WilyFreddie 您要访问的代码在哪里?可以评论指定吗!
  • @CoolVirus 我想从 matrix() 访问 m、n、p、q、first[MAX][MAX] 和 second[MAX]

标签: c arrays parameter-passing


【解决方案1】:

您可以将变量的地址传递给要在其中使用该变量的函数。

让我们举个例子,假设

#include<stdio.h>

void testing(int *);

int main(){

  int  x = 3;
  printf("%d\n" , x);

  testing(&x);
  printf("%d" , x);

   }

  void testing(int *j){
     *j = 8;
   }

输出将是 3 8 ,现在 x 在调用函数中更改,因为您将 x (&amp;x) 的地址传递给函数 testing 并使用 *j 取消引用该地址并将8 存储在j 指向的地址中,因此实际上x 发生了变化,因为您将其地址存储在一个现在指向该地址的指针中,然后将该地址传递给其他函数以及您取消引用的位置该地址(取消引用指针意味着获取存储在指针指向的内存位置中的值。运算符* 用于执行此操作,称为取消引用运算符)并更改了存储的值。

欲了解更多信息,请查看此问题What does "dereferencing" a pointer mean?

【讨论】:

    【解决方案2】:

    数组可以作为参数传递给函数;该函数将只接收指向第一个元素的指针,然后您将能够像原始数组一样对其进行索引。二维矩阵的第一个元素是一维矩阵;

    通常,数组的大小也必须以整数形式提供。

    在您的情况下,大小是已知且恒定的 (MAX),但无论如何您需要 2 个“大小”,即每个矩阵的行数和列数。您也可以简单地传递它们。

    下面的程序演示了传递一个标准数组,另外还展示了现代 C 可变长度数组的一个特性。

    #include<stdio.h>
    
    #define MAX 100
    
    // Pass  a matrix with constant number of columns
    // known at compile time, and the number of columns 
    // and rows we actually use.
    
    // Both declarations are ok. The first index is ignored.
    
    //void print(int mat[MAX][MAX])
    void print(int mat[][MAX], int usedRows, int usedCols)
    {
        for(int row=0; row<MAX && row<usedRows; row++)
        {
            for(int col=0; col<MAX && col<usedCols; col++)
            {
                printf("%5d", mat[row][col]);
            }
            printf("\n");
        }
    }
    
    // Pass a variable length array, together with its 
    // dimensions. Both declarations are ok.
    
    // void printVar(int rows, int cols, int vm[rows][cols])
    void printVar(int rows, int cols, int vm[][cols])
    {
        // demonstrate run-time sizeof(vm[row]).
        // one could use the sizeof construct instead of cols.
        printf("vla row length is %zd (cols: %d)\n",
                sizeof(vm[0])/sizeof(int), cols);
    
        for(int row=0; row<rows; row++)
        {
    
            for(int col=0; col<cols; col++)
            {
                printf("%5d", vm[row][col]);
            }
            printf("\n");
        }
    }
    
    int main() 
    {
        // matrix size known at compile time;
        // we fill only the first 3 rows and columns.
        int m[MAX][MAX] 
            =   {
                    {1, 2, 3},
                    {4, 5, 6},
                    {7, 8, 9}
                };
        // print the compile-time sized matrix. Function needs to know
        // how many rows and columns we actually used.  
        print(m, 3, 3);
    
        // Now use a feature of modern C: variable length arrays.
        {
            int numRows, numCols;
    
            printf("Now variable length array: ");
            printf("Please input two numbers, num rows and num columns: ");
            if( scanf("%d %d", &numRows, &numCols) != 2) 
            { 
                fprintf(stderr, "input error, aborting\n"); 
                return 1; 
            }
    
            // now define the matrix with the size the user requested.
            int varMat[numRows][numCols];
    
            // fill it with some data (cannot hard code, becase I
            // don't know the dimensions!)
            for(int row=0; row<numRows; row++)
            {
                for(int col = 0; col < numCols; col++)
                {
                    varMat[row][col] = row * numCols + col + 1;
                }
            }
    
            // And use the function for variable length array to print.
            printVar(numRows, numCols, varMat);
        }
        return 0;
    }
    

    示例会话:

    $ gcc -std=c11 -Wall -o matrixfuncs matrixfuncs.c && ./matrixfuncs
        1    2    3
        4    5    6
        7    8    9
    Now variable length array: Please input two numbers, num rows and num columns: 2 7
    vla row length is 7 (cols: 7)
        1    2    3    4    5    6    7
        8    9   10   11   12   13   14
    

    一个更好的解决方案是定义一个结构,该结构包含一个指向此类矩阵的指针和一个数据中的两个数字,这可以更容易地复制,但我必须假设结构将在您的课程中的数组之后被覆盖.

    【讨论】:

    • 我喜欢我的程序并认为它很好地回答了 OP 的问题。如果反对者可以指出答案的可能改进,我会很感激,OP 也是如此。
    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 2018-03-07
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多