0

I would like to ask why is that giving me seg fault.

  int **a = (int**) malloc (sizeof(int*) * 3);
  a[0][0] = 1;
  a[0][1] = 2;
  a[0][2] = 3;

  for(int i = 0; i < 3; i++)
  {
      printf("%d", a[0][i]);
      //but works with for instance: a[0][1]
  }

1 Answer 1

0

You are allocating memory for three pointers to int, but those are uninitialised, point to random places, not to memory to store actual ints in.

Either have mallocs for those pointers, too, or use statically sized arrays instead of pointers to int.

3
  • I just needed to make those pointers to point to another pointers with values and all is well:D Unless I was just lucky haha
    – Kamil Kug
    Commented Feb 3, 2017 at 13:33
  • You are lucky if a[0][0] = 1; not already blows up that code you posted, as value of a[0] is not initialized, and you dereference it.
    – Blauelf
    Commented Feb 3, 2017 at 13:55
  • I did malloced memory to each a** pointer and than added more memory at single a* level of this pointer and this way I could insert values:) If that makes sense.
    – Kamil Kug
    Commented Feb 3, 2017 at 14:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .