1

What is wrong with the following code? It generates a Segmentation fault.

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

typedef struct{
    int ** access;
}item;

int main()
{

    int access[5][5];

    for(int i = 0; i < 5; i++){
        for(int j = 0; j<5; j++){
            access[i][j] = 5;
        }
    }

    item * p = malloc(sizeof(item));
    p->access = access;

    for(int i = 0; i < 5; i++){
        for(int j = 0; j<5; j++){
            printf("%d",p->access[i][j]);
        }
    }


    return 0;
}

I want to create a struct that contains the value of a double array created in the main function. What is wrong with it?

Billy
  • 701
  • 1
  • 8
  • 26
  • Does this answer your question? [Why can't we use double pointer to represent two dimensional arrays?](https://stackoverflow.com/questions/4470950/why-cant-we-use-double-pointer-to-represent-two-dimensional-arrays) – kaylum Nov 30 '19 at 21:52
  • 1
    Never ignore compiler warnings: *"warning: assignment to `int **` from incompatible pointer type `int (*)[5]` [-Wincompatible-pointer-types]"* – UnholySheep Nov 30 '19 at 21:52
  • Coding issues aside, why are you dynamically allocating an item but then having its `access` member point to an automatic variable (`access`)? Seems like a dangerous pattern. – jarmod Dec 01 '19 at 17:09

1 Answers1

0

You can have array of pointer in your struct like int *[5]. But you have to assign address of each row in 2D array to struct data member.

Also free your memory allocated in malloc.

anuplohiya
  • 46
  • 3