Pointer on pointer inaccuracies

I was working with 2D arrays and was trying to pass it from one function to another. I've seen all the answers here regarding this and none of them seem to have answered this particular type of problem. Its a simple thing I am trying to achieve, but the answer is weird.

Here's main ():

int main(void)
{   
 int i=0,j=0,n=0,n2=0;    
 double **a, **a1, b=0; 

 printf("Enter 'n2' :");
 scanf("%d", &n2);


 a= makearray(n2);
 for(i=0; i < n2; i++){
     for(j=0; j < n2; j++){         
         a[i][j] = j;
         printf("%.f ",a[i][j]);
    }
     printf("\n");
  }

 printf("\n\n\n");

 for(i=0; i < n2; i++){ // print a
      for(j=0; j < n2; j++){
         b = a[i][j];
         printf("%.f ", b);
     }
     printf("\n");
 }

 printf("\n\n\n");
 return 0;
}  

      

The makearray () function simply returns a pointer to a pointer for the two-dimensional array of size passed as an argument.

makearray ():

double** makearray(int n2)
{
int i=0;
double** a;

a = malloc(n2 * sizeof(int *));
if(a == NULL){
    fprintf(stderr, "out of memory\n");
    exit(0);
    }

for(i = 0; i < n2; i++){
    a[i] = malloc(n2 * sizeof(int));
    if(a[i] == NULL){
        fprintf(stderr, "out of memory\n");
        exit(0);
        }
    }

return a;

}

      

You can enter "n2" where (n2 x n2) becomes the size of the matrix, and with n = 9 the output is:

0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 

0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 0 1 2
0 1 2 3 4 5 6 7 8 

      

I didn't change the first array in any way, just printed it again, any ideas why these two are different?

+3


source to share


2 answers


Your makearray is malloc

used sizeof(int)

, but you create an array for double

s. Ints are commonly used 4 bytes

but double

used 8 bytes

. So you don't malloc

- have enough memory for a 2D array of doublings.



+3


source


Try:



double** makearray(int n2)
{
int i=0;
double** a;

a = malloc(n2 * sizeof(double *)); //<- was sizeof(int *)
if(a == NULL){
    fprintf(stderr, "out of memory\n");
    exit(0);
    }

for(i = 0; i < n2; i++){
    a[i] = malloc(n2 * sizeof(double)); //<- was sizeof(int)
    if(a[i] == NULL){
        fprintf(stderr, "out of memory\n");
        exit(0);
        }
    }

return a;

}

      

+3


source







All Articles