0

i have an array, int* array, with more than 10.000 int values, but i want to point to each 100 position, it means that I will have int ** matrix, where:
matrix[i][j], I want i from my matrix to point to array[i * 100], how can y substitute the address ? here is what I've done:

u_int8_t **matrix = (u_int8_t **)malloc(width * sizeof(u_int8_t *));

int width_cr = 0;
for (int i = 0; i < width; i ++) {
    if (i % 100 == 0) {

        u_int8_t *position = matrix[width_cr];
        position = &array[i];
        width_cr ++;           

    }
}

the problem is that it points to the beginning of the array

Matt
  • 22,721
  • 17
  • 71
  • 112
Florik
  • 1,260
  • 1
  • 12
  • 20
  • 2
    [You should not cast the return of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Eregrith Sep 13 '12 at 12:51
  • 2
    Unrelated, but you should change your loop increment to `i += 100` and remove the `if`. – verdesmarald Sep 13 '12 at 12:51
  • @RichardChambers I'm pretty sure the OP just wants to build a 2d array that indexes into an existing 1d array. – verdesmarald Sep 13 '12 at 13:08
  • Not sure, but I think this can be done with a union (assuming size is static). – Neil Sep 13 '12 at 13:09
  • yes i need to do 2d array, without to copy the whole bytes, i need just to point in matrix[i * 100][23], so if i is 3, it will point to 323 from the 1d array – Florik Sep 13 '12 at 13:13

1 Answers1

2

Store the address of array[i] in matrix[i / 100].

#define HOW_MUCH_NUMBERS 10000

[...]
{
  int array[HOW_MUCH_NUMBERS];
  int i = 0;
  int **matrix;

  matrix = malloc(sizeof(*matrix) * (HOW_MUCH_NUMBERS / 100));
  while (i < HOW_MUCH_NUMBERS)
  {
    matrix[i / 100] = &array[i];
    i += 100;
  }
  [...]
}
Eregrith
  • 4,263
  • 18
  • 39