0

Why can I not access Lattice using [ ][ ] without raising a seg fault?

int *LatticeHeight;
int **Lattice;

LatticeHeight = (int*)malloc(Height*sizeof(int));

Lattice = (int**)malloc(Length*sizeof(LatticeHeight));

for(i=0;i<Height; i++)
    {
    for(j=0; j<Length; j++)
    {
        Lattice[j][i] = 0;
    }
}

I'm interpreting this as;

I have my pointer to one dimensional array of height

Then I set Lattice so that is can store Length-many copies of LatticeHeight (making a grid)

Then I access each element of the lattice and set it's value to 0

Moreover could someone explain why this works in 1D but not in 2D, i.e.

for(i=0;i<Height;i++)
{
    LatticeHeight[i] = 0;
}

Does not throw a seg fault

Aaron
  • 311
  • 3
  • 9

3 Answers3

2

You didn't allocate the array properly. Your first malloc allocates one row; your second malloc allocates space to store a pointer to each row but it does not actually allocate any rows to go in there (and it does not have any association to the single row you allocated earlier, either).

The simplest way to write this code, if you do not require to have rows of different lengths to each other, is to allocate a single memory block:

int (*Lattice)[Length] = calloc( Height, sizeof *Lattice );

If you do want to have a jagged array for some reason (i.e. each row is allocated in a separate memory block) then the code is:

int **Lattice = malloc( Height * sizeof *Lattice );
for ( size_t row = 0; row != Height; ++row )
    Lattice[row] = calloc( Length * sizeof **Lattice );

Note that calloc allocates the memory and also zeroes it, so you don't need your zero loop afterwards, and don't cast malloc

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • "height" being the number of rows, and "length" being the number of columns is the usual convention in C, I'd recommend adopting it in case you ever work with anybody else on a project :) – M.M Dec 13 '14 at 03:39
0

You have to allocate memory for Lattice which is a pointer to a pointer to int.

Lattice = malloc(Length * sizeof(LatticeHeight));

And then iterate through the "array" of pointers to int that you just have created and allocate memory for each one, like this.

for(i = 0; i < Lenght; i++)
    LatticeHeight = malloc(Height * sizeof(int));

With that you would have a two-dimensional "array".

Although, as Matt McNabb said, there are other options for what you want to do.

Patricio Sard
  • 2,092
  • 3
  • 22
  • 52
0

I think you should initialize your array like this:

Lattice = (int**)malloc(Length*sizeof(int*));
for(int i = 0; i < Length; ++i) {
    LatticeHeight =  (int*)malloc(Height*sizeof(int));
}
vmcloud
  • 650
  • 4
  • 13