使变量可由C中的其他函数访问

时间:2017-01-24 11:31:11

标签: c arrays parameter-passing

我是编程新手,我们刚刚在课堂上学习过数组 我们的任务是在不使用全局变量的情况下创建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;
}
}

2 个答案:

答案 0 :(得分:2)

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

让我们举一个例子,假设

#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&x)的地址传递给函数testing并且通过使用*j,您将取消引用该地址并将8存储在j指向的地址中,因此实际上x会更改,因为您将其地址存储在指针中现在指向该地址,然后将该地址传递给其他函数,并取消引用该地址(取消引用指针意味着获取存储在指针指向的内存位置的值。运算符*用于执行此操作,并将其称为解除引用运算符)并更改存储的值。

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

答案 1 :(得分:-1)

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

通常,必须提供数组的大小,作为整数。

在你的情况下,尺寸是已知的并且是常数(MAX),但是你需要2&#34;尺寸&#34;,即每个矩阵的行数和列数。您也可以简单地传递它们。

下面的程序演示了传递标准数组,并且还提供了现代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

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

相关问题