0

I am doing something like following;

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


typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;  
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));


   return 0;
}

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?

3 Answers3

1

You have not allocated memory to your comm variable.

Also count is uninitialized.

machine_1
  • 4,266
  • 2
  • 21
  • 42
Eraklon
  • 4,206
  • 2
  • 13
  • 29
1

Either you do this :

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


typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication comm;
    comm.arr = malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm.arr[i] = malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm.arr[i][j] = count*2.0;  
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm.arr[i]+j));


   return 0;
}

Or this :

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


typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm = malloc(sizeof(communication));
    comm->arr = malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;  
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));


   return 0;
}
Doliprane
  • 151
  • 5
1

You have to allocate the memory for comm variable like the allocation of arr. Because comm is pointer, the defaut value may be NULL. So, you cannot point to the array arr inside of the struct communication.

Add this code below, your program will be work well:

 communication *comm = (communication *) malloc (sizeof(communication));
Hitokiri
  • 3,607
  • 1
  • 9
  • 29