3

I'm really a beginner in C programming language, and i've started learning pointers... I have some problems manipulating them. What i want to do is to read and write a matrix, with 2 functions, without using global variables (just pointers)... So I did not succed making this. I've searched a lot about pointers and I try to understand how i can use them , but i'm not able to read and write that matrix What i do wrong ...Please, please, please help me (Even with some Useful links about 2DArray & pointers)...Thank you!

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

void readM(int (*x)[100][100], int *row, int *column)
{
int i,j;
printf("Row no: ");
scanf("%d",row);
printf("Column no: ");
scanf("%d",column);
printf("Matrix elemnts: \n");    
for(i=0;i<(*row);i++)
{
    for(j=0;j<(*column);j++)
    {
        printf("[%d][%d]=",i,j);
        scanf("%d",x[i][j]);
    }
}
}

void writeM(int (*x)[][100], int *row, int *column)
{
int i,j;
printf("\nMatrix is: \n");
for(i=0;i<(*row);i++){
    for (j=0;j<(*column);j++){
    printf("%d",(*x)[i][j]);
    }
    printf("\n");
    }
}

int main()
{

char choice;
int a[100][100],m,n;
do
{
   printf("\nChose an option\n\n"
      "1) read matrix \n"
      "2) write matrix\n"
      "3) display matrix in spiral\n"
      "4) return max and min\n"
      ///...etc
   scanf("%c", &choice);
   while (choice<'0'|| choice>'4')
         {
            printf("\nInvalid option! Chose again! \n\n");
            scanf("%c",&choice);
         }
   switch (choice)
   {
        case '0': exit(0);
        case '1': readM(&a,&m,&n); break;
        case '2': writeM(&a,&m,&n);break; /// ... etc
} while (choice !=5);
getch();
}
4

2 回答 2

2

There probably would be more than one mistakes

Using scanf with %s for a single char variable. If you wanna input a char, use %c (better yet, use getc or getchar) since scanf has it's own issues. Or pass a char array to %s. But then you can't compare a string with a char like you did in

choice<'0'

Also remove the '\n' before scanf. In printf \n flushes the buffer and moves to next line. In case of scanf, adding it after the %c or %s still makes some sense (as you are indicating a terminator), but certainly not before it.

There is no function pointer here. They are used to pass functions as parameters. You are merely passing an array which is passed by reference by default. So simply use

int x[100][100] or int x[][100]

in parameters of function definitions and treat x as an array like

x[a][b] rather than *x[a][b]

Also when passing array from main simply pass 'a' which is the name of array that is passed by reference itself. Passing address of an array is meaningless.

于 2012-11-03T20:08:07.520 回答
2

另一个问题是,当您读取数组时,您首先跟随指针 (*x),然后添加数组偏移量 [i][j]:这可能会将您带到一些您甚至没有的内存位置进入。由于您传递的是指针数组,因此您将首先查看数字位置 (x[i][j]),然后跟随指针。

编辑:之前的用户更新了他的答案以反映我在这里给出的第二个建议,所以我删除了它。

于 2012-11-03T20:19:10.560 回答