cpointersarray-address

Point to specific value of an array


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


Solution

  • 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;
      }
      [...]
    }