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]
  }
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.

| improve this answer | |
  • 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 Feb 3 '17 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 Feb 3 '17 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 Feb 3 '17 at 14:52

You must log in to answer this question.

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