reading a matrix

hello every one. I have a small problem. I keep get an error when i'm trying to read a matrix. I'm using C programming style cuse this is what they ask at school :(

Here is my reading function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void citire(int ***a,int *m,int *n)
{
	int i,j;

	printf("m=");scanf("%d",m);
	printf("n="); scanf("%d",n);
	
	(*a)=(int**)malloc((*m)*sizeof(int*));
	for(i=0;i<*m;i++) (*a)[i]=(int*)malloc((*n)*sizeof(int));

	for(i=0;i<*m;i++)
		for(j=0;j<*n;j++)
		{
			printf("[%d][%d]=",i,j);
			scanf("%d",a[i][j]); 
		}
}


And here is the part from the main function that calls the reading one.
1
2
int **a,m,n;
citire(&a, &m, &n);


The error appears after I insert the first row in the matrix (when i=1), so is not an compilating error, is an trow exception that tells me:
Unhandled exception at 0x00D3163B in Toaca_Cristian.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.

So can anyone tell me what to do to make the program work ?
My solution is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdlib.h>
#include <stdio.h>

int citire(int ***a,int *m,int *n)
{
  int i,j;
  printf("m=");scanf("%d",m);
  printf("n="); scanf("%d",n);
  *a=(int**)malloc((*m)*sizeof(int *));
  if (*a == NULL){
    printf("ERROR: out of memory\n");
    return 1;
  }
  for(i=0;i<*m;i++){
    (*a)[i]=(int*)malloc((*n)*sizeof(int));
    if ((*a)[i] == NULL){
      printf("ERROR: out of memory\n");
      return 1;
    }
  }
  for(i=0;i<*m;i++)
    for(j=0;j<*n;j++)	{
      printf("[%d][%d]=",i,j);
      scanf("%d",&(*a)[i][j]); 
    }
}

int main() {
  int **a,m,n;
  int i,j;
  if (citire(&a, &m, &n) == 0){
    for (i=0;i<m;i++){
      for (j=0;j<n;j++)printf("%d",a[i][j]);
        printf("\n");
    }
  } else {
    printf("\n ERROR IN ARRAY ALLOCATION!");
  }
  return 0;
}


Please, forgive me if I added some safety checks after all the dynamical allocations of memory. It helped me in testing your code so I left it :)
The problem was in the scanf. Allocating the array in this way, the rows are not allocated in contiguous locations of memory. So you need the fun trick I used to properly deference the array pointer. Other solution are possible. Hope it can help.
Last edited on
Topic archived. No new replies allowed.