I am learning C and I am trying to have a virtual grid in it, where the user can put new grid elements to "activate" into the console. So for example if I am starting with nothing and the user adds (40,50), then the size is at least 40x50 with element (40,50) initialised. If (20,30) follows, it just activates the element at 20,30. But if the user then enters (500,300), it will allocate some more memory and increases the size of the array. I would like to access them easily. I would like to work (I might have to anyway), because they are new for me.
My code (at the moment) is the following:
int width = 4, height = 5;
bool **arr = (bool **) malloc(height * sizeof(bool *));
for (int x = 0; x < height; x++) {
arr[x] = (bool *) malloc(width * sizeof(bool));
}
for (int x = 0; x < height; x++) {
for (int y = 0; y < width; y++) {
*(*(arr + x) + y) = false;
}
}
*(*(arr + 3) + 2) = true;
// user puts a value bigger than (4,5) inside
int newX=10, newY = 10;
//allocate more memory
So I am using a 2D pointer with booleans and I do "malloc" the height first and afterwards make an array of them for the width.
In the last line is just an example of entering the first element at (2,3). The scan method for the user doesn't matter here.
So is there a way of increasing the size of my array afterwards or do I need a totally different concept for it?
=====
The current code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main() {
int width = 4, height = 5;
bool **arr = (bool **) malloc(height * sizeof(bool *));
for (int x = 0; x < height; x++) {
arr[x] = (bool *) malloc(width * sizeof(bool));
}
for (int x = 0; x < height; x++) {
for (int y = 0; y < width; y++) {
*(*(arr + x) + y) = false;
}
}
*(*(arr + 3) + 2) = true;
int newWidth = 10, newHeight = 10;
bool **narr = realloc(arr, newHeight * sizeof(bool*));
if(narr) {
arr = narr;
for(size_t i = 0; i < newHeight; i++){
bool* p = realloc(arr[i] , newWidth * sizeof(bool));
if( !p ){
perror("realloc");
}
arr[i] = p;
}
// here resize the number of elements if needed
}
else {
perror("realloc failed");
exit(EXIT_FAILURE);
}
return 0;
}
Yes there is a mathod called realloc. And you can use that. You can resize the jagged array completely.
bool **narr = realloc(arr , newsize * sizeof(bool*));
if( narr ) {
arr = narr;
for(size_t i = 0; i < newsize; i++){
bool* p = realloc(arr[i] , newsize1 * sizeof(bool));
if( !p ){
perror("realloc");
}
arr[i] = p;
}
// here resize the number of elements if needed
}
else {
perror("realloc failed");
exit(EXIT_FAILURE);
}
Also simplify things write a[1][2] instead of *(*(a+1)+2). The check is needed as realloc may fail - in that case instead of letting your code go awry, take appropriate step as needed.
Also note that you need to set all the newly allocated bool* to NULL. So do this:-
for(size_t i = 0; i < newHeight; i++){
if( i >= height)
arr[i] = NULL;
bool* p = realloc(arr[i] , newWidth * sizeof(bool));
if( !p ){
perror("realloc");
}
arr[i] = p;
}
This is needed because realloc expects address of memory previously allocated with *alloc functions or NULL.
You can use realloc to increase the size of the array
in your situation you'd do
arr = (bool **)realloc(arr, sizeof(bool*) * new_height)
for(int i = 0; i < new_height; i++){
arr[i] = (bool *)realloc(arr, sizeof(bool) * new_width);
}
Note that you have to check whether the array needs to even get bigger, realloc can also "shrink" your array so tread carefully.
Initializing the newly created memory to false:
for(int i = old_height; i < new_height; i++){
for(int j = old_width; j < new_width; j++){
arr[i][j] = false;
}
}
arr[new_height - 1][new_width - 1] = true;
Related
I am a bit of a beginner in C language. I was trying out a task of dynamically reallocating memory as the input comes through(although for this test I am doing a normal task, later will try to scale it up). the issue I am facing is I am unable to access the memory while writing into it. Can anyone please help me understand where I am going wrong in this code. thanks in advance.
code:
#include<stdio.h>
#include<stdlib.h>
struct ai {
int* a;
char* b;
};
int main()
{
struct ai *test;
test = (struct ai*) malloc(sizeof(struct ai));
test[0].a = (int*)malloc(sizeof(int));
test[0].b = (char*)malloc(sizeof(char));
/// storing info
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
test[i].a[j] = j;
test[i].b[j] = 65 + j;
test[i].a = (int *) realloc(test[i].a, (j + 2) * sizeof(int));
test[i].b = (char*) realloc(test[i].b, (j + 2) * sizeof(char));
}
test = (struct ai*)realloc(test, (i + 2) * sizeof(struct ai));
}
// printing the block out
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d , %c\n", test[i].a[j], test[i].b[j]);
}
}
return 0;
} ```
You have missing initialization of your pointers and some other issues...
int main()
{
struct ai *test;
test = (struct ai*) malloc(sizeof(struct ai));
test[0].a = (int*)malloc(sizeof(int));
test[0].b = (char*)malloc(sizeof(char));
In C you should not cast the result of malloc. In best case it is useless. In worst case it hides real problems.
/// storing info
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
test[i].a[j] = j;
test[i].b[j] = 65 + j;
Here comes the reason for your segmentation fault:
You do not have any memory reserved for a and b except for the first element test[0]. All other array elements test[i] do not contain any useful data. Dereferencing these pointers is undefined behaviour.
You must allocate memory for each field after you enlarged your array.
test[i].a = (int *) realloc(test[i].a, (j + 2) * sizeof(int));
test[i].b = (char*) realloc(test[i].b, (j + 2) * sizeof(char));
You should never assign the return value of realloc to the same variable that you passed into the function. In case of an error you will get NULL return value and then your initiali pointer is lost.
Also here: don't cast for realloc as well.
}
test = (struct ai*)realloc(test, (i + 2) * sizeof(struct ai));
Same here: Don't assign to same variable and don't cast the result of realloc.
Finally: Here goes the missing part:
test[i+1].a = malloc(sizeof(*test[0].a));
test[i+1].b = malloc(sizeof(*test[0].b));
}
Of course you should check all return values for error results.
Not related to the segmentation fault, but still worth to fix:
You increment the size of each array after you used the last element.
This prepares the new element for being filled in next iteration of the loops. But in case of the last iteration it allocated an unused element for both the intern pointers a and b as well as the outer array test.
You will have some unused elements:
test[0].a[4]
test[0].b[4]
test[1].a[4]
test[1].b[4]
test[2].a[0]
test[2].b[0]
An improved solution could look like this (not tested)
I start with each pointer being NULL and use realloc right before the new element is used to avoid the extra elements.
int main(void)
{
struct ai *test = NULL
void *tmp;
// storing info
for (int i = 0; i < 2; i++)
{
tmp = realloc(test, (i+1) * sizeof(*test))
if (tmp == NULL)
exit(1);
test = tmp;
test[i].a = NULL;
test[i].b = NULL;
for (int j = 0; j < 4; j++)
{
tmp = realloc(test[i].a, (j+1) * sizeof(test[i].a[0]));
if (tmp == NULL)
exit(1);
test[i].a = tmp;
tmp = realloc(test[i].b, (j+1) * sizeof(test[i].b[0]));
if (tmp == NULL)
exit(1);
test[i].b = tmp;
test[i].a[j] = j;
test[i].b[j] = 65 + j;
}
}
// printing the block out
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d , %c\n", test[i].a[j], test[i].b[j]);
}
}
return 0;
}
I'm suppose to implement in the function make2Darray to make the elements in the 2D array correspond with the row number.
The other parts of the code that prints and frees was already given, so no need to worry about that. I'm only suppose to touch the make2Darray function. However, in that function, the allocating part was also given. So the only code I am to alter is the part where I change the elements in the 2D array.
int** make2Darray(int width, int height) {
int **a;
int i = 0;
int j = 0;
/*allocate memory to store pointers for each row*/
a = (int **)calloc(height, sizeof(int *));
if(a != NULL) {
/* allocate memory to store data for each row*/
for(i = 0; i < height; i++) {
a[i] = (int *)calloc(width, sizeof(int));
if(a[i] == NULL) {
/* clean up */
free2Darray(a, height);
return NULL; /*aborting here*/
}
}
}
/* from this point down is the part I implemented, all code above was
given*/
if (height < 0 && width < 0) {
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
a[i][j] = j;
}
}
}
return a;
}
The elements in the 2D array is suppose to correspond to the row number
If height = 4 and width = 3
0 0 0
1 1 1
2 2 2
3 3 3
However, I always get 0s which was the default setting when I got the code
0 0 0
0 0 0
0 0 0
0 0 0
You have two major problems in the code.
1) The code where you initialize the 2D array shall be inside the if-block
2) if (height < 0 && width < 0) { is wrong - you want > instead of <
Try:
int** make2Darray(int width, int height) {
int **a;
int i = 0;
int j = 0;
/*allocate memory to store pointers for each row*/
a = (int **)calloc(height, sizeof(int *));
if(a != NULL) {
/* allocate memory to store data for each row*/
for(i = 0; i < height; i++) {
a[i] = (int *)calloc(width, sizeof(int));
if(a[i] == NULL) {
/* clean up */
free2Darray(a, height);
return NULL; /*aborting here*/
}
}
// Moved inside the if(a != NULL) {
/* from this point down is the part I implemented, all code above was
given*/
if (height > 0 && width > 0) { // Corrected this part
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
a[i][j] = j;
}
}
}
}
return a;
}
A few hint:
1) Do the check for height and width in the beginning of your function - like:
if (height <= 0 || width <= 0) return NULL;
2) The prototype make2Darray(int width, int height) seems backward to me as we normally mention row-count before column-count. I would prefer: make2Darray(int height, int width). I even prefer the term "row" instead of "height" and "column" instead "width".
3) Your current code do "all the real stuff" inside the if(a != NULL) { That's okay but the code would (to me) be more clear if you instead did if(a == NULL) return NULL;
4) No need to cast calloc
With these updates the code could be:
int** make2Darray(int rows, int columns) {
int **a;
int i = 0;
int j = 0;
if (rows <= 0 || columns <= 0) return NULL;
a = calloc(rows, sizeof(int*));
if(a == NULL) return NULL;
/* allocate memory to store data for each row*/
for(i = 0; i < rows; i++) {
a[i] = calloc(columns, sizeof(int));
if(a[i] == NULL) {
/* clean up */
free2Darray(a, rows);
return NULL; /*aborting here*/
}
}
/* from this point down is the part I implemented, all code above was
given*/
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
a[i][j] = j;
}
}
return a;
}
In your code, the if check seems out of place.
if(a != NULL) {
/* allocate memory to store data for each row?
for(i = 0; i < height; i++) {
a[i] = (int *)calloc(width, sizeof(int));
if(a[i] == NULL) {
/* clean up */
free2Darray(a, height);
return NULL; /*aborting here*/
}
Well, that makes no sense. In case of success, a is supposed to be not equal to NULL.
You should rather have a check for a == NULL and subsequently return NULL;, not the other way around.
That said:
if (height < 0 && width < 0) does not look very good. It's most likely wrong (in this usage context) and counter productive.
All the access for a[i][j] is invalid. You just have the space allocated for the int *s, the int *s themselves do not point to any valid memory. You need to allocate memory to them also (for example, using the width as size).
I have two arrays (representing rooms) with items that are traveling through the space. I found an interesting way to allocate the ram here in the forum. Here is what I am doing:
First I create an empty room with some default values.
After that I put some elements into it. There are two different items. An obstacle and an item that travels through the room. I have an iteration that runs for example 100 times and puts all items one coordinate further. The obstacles keep their position.
Every iteration has to do the following:
First it creates a new temporary room (new_room). It copies all obstacles because they stay at the same place(id = 3). Next, every item from the old room(room) gets his new coordinate in the new_room. After that I change the rooms, so room gets new_room. I have some big problems with the memory usage. I want to free the old new_room every time I create a new one with createRoomNew().In this implementation I get a segmentation fault. I think because of the function changeroom().
I am really confused right now because I am new to C.... I hope I pointed out what I mean. Thank you very much!
item_node ***room;
item_node ***room_new;
void createRoom(int x, int y, int z)
{
if (room == NULL) {
item_node *allElements = malloc(x * y * z * sizeof(item_node));
room = malloc(x * sizeof(item_node **));
for(int i = 0; i < x; i++)
{
room[i] = malloc(y * sizeof(item_node *));
for(int j = 0; j < y; j++)
{
room[i][j] = allElements + (i * y * z) + (j * z);
}
}
for (j = 0; j < x_format; j++) {
for (k = 0; k < y_format; k++) {
for (l = 0; l < z_format; l++) {
room[j][k][l].id = 3;
room[j][k][l].next = NULL;
}
}
}
}
}
void createRoomNew(int x, int y, int z)
{
if (room_new != NULL) {
for(int i = 0; i < x; i++)
{
free(room_new[i]);
}
free (room_new);
room_new = NULL;
}
if (room_new == NULL) {
item_node *allElements = malloc(x * y * z * sizeof(item_node));
room_new = malloc(x * sizeof(item_node **));
for(int i = 0; i < x; i++)
{
room_new[i] = malloc(y * sizeof(item_node *));
for(int j = 0; j < y; j++)
{
room_new[i][j] = allElements + (i * y * z) + (j * z);
}
}
}
for (j = 0; j < x_format; j++) {
for (k = 0; k < y_format; k++) {
for (l = 0; l < z_format; l++) {
if ((room[j][k][l].next) != NULL) {
if ((room[j][k][l].next->id) == 1) {
room_new[j][k][l] = room[j][k][l];
} else {
room_new[j][k][l].id = 3;
room_new[j][k][l].next = NULL;
}
}
else {
room_new[j][k][l].id = 3;
room_new[j][k][l].next = NULL;
}
}
}
}
}
void changeRoom(item_node *** newRoom)
{
room = newRoom;
}
Example call:
createRoom(200, 200, 200);
createRoomNew(200, 200, 200);
changeRoom(room_new);
createRoomNew(200, 200, 200);
changeRoom(room_new);
From the code it seems you think that when you do free, e.g. free(room_new) that room_new ends up being set to NULL. That is not the case
free() doesn't set a pointer to NULL (it can't), it is still pointing to wherever it was pointing just that the memory is no longer usable. You need to manually set the pointer to NULL after freeing.
I'd like to allocate a 3D matrix in one big chunk. It should be possible to access this matrix in the [i][j][k] fashion, without having to calculate the linearized index every time.
I think it should be something like below, but I'm having trouble filling the ...
double ****matrix = (double ****) malloc(...)
for (int i = 0; i < imax; i++) {
matrix[i] = &matrix[...]
for (int j = 0; j < jmax; j++) {
matrix[i][j] = &matrix[...]
for (int k = 0; k < kmax; k++) {
matrix[i][j][k] = &matrix[...]
}
}
}
For the single allocation to be possible and work, you need to lay out the resulting memory like this:
imax units of double **
imax * jmax units of double *
imax * jmax * kmax units of double
Further, the 'imax units of double **' must be allocated first; you can reorder the other two sections, but it is most sensible to deal with them in the order listed.
You also need to be able to assume that double and double * (and double **, but that's not much of a stretch) are sufficiently well aligned that you can simply allocate the chunks contiguously. That is going to hold OK on most 64-bit systems with type double, but be aware of the possibility that it does not hold on 32-bit systems or for other types than double (basically, the assumption could be problematic when sizeof(double) != sizeof(double *)).
With those caveats made, then this code works cleanly (tested on Mac OS X 10.10.2 with GCC 4.9.1 and Valgrind version valgrind-3.11.0.SVN):
#include <stdio.h>
#include <stdlib.h>
typedef double Element;
static Element ***alloc_3d_matrix(size_t imax, size_t jmax, size_t kmax)
{
size_t i_size = imax * sizeof(Element **);
size_t j_size = imax * jmax * sizeof(Element *);
size_t k_size = imax * jmax * kmax * sizeof(Element);
Element ***matrix = malloc(i_size + j_size + k_size);
if (matrix == 0)
return 0;
printf("i = %zu, j = %zu, k = %zu; sizes: i = %zu, j = %zu, k = %zu; "
"%zu bytes total\n",
imax, jmax, kmax, i_size, j_size, k_size, i_size + j_size + k_size);
printf("matrix = %p .. %p\n", (void *)matrix,
(void *)((char *)matrix + i_size + j_size + k_size));
Element **j_base = (void *)((char *)matrix + imax * sizeof(Element **));
printf("j_base = %p\n", (void *)j_base);
for (size_t i = 0; i < imax; i++)
{
matrix[i] = &j_base[i * jmax];
printf("matrix[%zu] = %p (%p)\n",
i, (void *)matrix[i], (void *)&matrix[i]);
}
Element *k_base = (void *)((char *)j_base + imax * jmax * sizeof(Element *));
printf("k_base = %p\n", (void *)k_base);
for (size_t i = 0; i < imax; i++)
{
for (size_t j = 0; j < jmax; j++)
{
matrix[i][j] = &k_base[(i * jmax + j) * kmax];
printf("matrix[%zu][%zu] = %p (%p)\n",
i, j, (void *)matrix[i][j], (void *)&matrix[i][j]);
}
}
/* Diagnostic only */
for (size_t i = 0; i < imax; i++)
{
for (size_t j = 0; j < jmax; j++)
{
for (size_t k = 0; k < kmax; k++)
printf("matrix[%zu][%zu][%zu] = %p\n",
i, j, k, (void *)&matrix[i][j][k]);
}
}
return matrix;
}
int main(void)
{
size_t i_max = 3;
size_t j_max = 4;
size_t k_max = 5;
Element ***matrix = alloc_3d_matrix(i_max, j_max, k_max);
if (matrix == 0)
{
fprintf(stderr, "Failed to allocate matrix[%zu][%zu][%zu]\n", i_max, j_max, k_max);
return 1;
}
for (size_t i = 0; i < i_max; i++)
{
for (size_t j = 0; j < j_max; j++)
{
for (size_t k = 0; k < k_max; k++)
matrix[i][j][k] = (i + 1) * 100 + (j + 1) * 10 + k + 1;
}
}
for (size_t i = 0; i < i_max; i++)
{
for (size_t j = 0; j < j_max; j++)
{
for (size_t k = k_max; k > 0; k--)
printf("[%zu][%zu][%zu] = %6.0f\n", i, j, k-1, matrix[i][j][k-1]);
}
}
free(matrix);
return 0;
}
Example output (with some boring bits omitted):
i = 3, j = 4, k = 5; sizes: i = 24, j = 96, k = 480; 600 bytes total
matrix = 0x100821630 .. 0x100821888
j_base = 0x100821648
matrix[0] = 0x100821648 (0x100821630)
matrix[1] = 0x100821668 (0x100821638)
matrix[2] = 0x100821688 (0x100821640)
k_base = 0x1008216a8
matrix[0][0] = 0x1008216a8 (0x100821648)
matrix[0][1] = 0x1008216d0 (0x100821650)
matrix[0][2] = 0x1008216f8 (0x100821658)
matrix[0][3] = 0x100821720 (0x100821660)
matrix[1][0] = 0x100821748 (0x100821668)
matrix[1][1] = 0x100821770 (0x100821670)
matrix[1][2] = 0x100821798 (0x100821678)
matrix[1][3] = 0x1008217c0 (0x100821680)
matrix[2][0] = 0x1008217e8 (0x100821688)
matrix[2][1] = 0x100821810 (0x100821690)
matrix[2][2] = 0x100821838 (0x100821698)
matrix[2][3] = 0x100821860 (0x1008216a0)
matrix[0][0][0] = 0x1008216a8
matrix[0][0][1] = 0x1008216b0
matrix[0][0][2] = 0x1008216b8
matrix[0][0][3] = 0x1008216c0
matrix[0][0][4] = 0x1008216c8
matrix[0][1][0] = 0x1008216d0
matrix[0][1][1] = 0x1008216d8
matrix[0][1][2] = 0x1008216e0
matrix[0][1][3] = 0x1008216e8
matrix[0][1][4] = 0x1008216f0
matrix[0][2][0] = 0x1008216f8
…
matrix[2][2][4] = 0x100821858
matrix[2][3][0] = 0x100821860
matrix[2][3][1] = 0x100821868
matrix[2][3][2] = 0x100821870
matrix[2][3][3] = 0x100821878
matrix[2][3][4] = 0x100821880
[0][0][4] = 115
[0][0][3] = 114
[0][0][2] = 113
[0][0][1] = 112
[0][0][0] = 111
[0][1][4] = 125
[0][1][3] = 124
[0][1][2] = 123
[0][1][1] = 122
[0][1][0] = 121
[0][2][4] = 135
…
[2][2][0] = 331
[2][3][4] = 345
[2][3][3] = 344
[2][3][2] = 343
[2][3][1] = 342
[2][3][0] = 341
There is a lot of diagnostic output in the code shown.
This code will work with C89 (and C99 and C11), without requiring support for variable-length arrays or VLAs — though since I declare variables in for loops, the code as written requires C99 or later, but it can easily be fixed to declare the variables outside the for loops and it can then compile with C89.
This can be done with one simple malloc() call in C (not in C++, though, there are no variable length arrays in C++):
void foo(int imax, int jmax, int kmax) {
double (*matrix)[jmax][kmax] = malloc(imax*sizeof(*matrix));
//Allocation done. Now fill the matrix:
for(int i = 0; i < imax; i++) {
for(int j = 0; j < jmax; j++) {
for(int k = 0; k < kmax; k++) {
matrix[i][j][k] = ...
}
}
}
}
Note that C allows jmax and kmax to be dynamic values that are only known at runtime. That is the ability that's missing in C++, which makes C arrays much more powerful than their C++ counterpart.
The only drawback of this approach, as WhozCraig rightly notes, is that you can't return the resulting matrix as the return value of the function without resorting to a void*. However, you can return it by reference like this:
void foo(int imax, int jmax, int kmax, double (**outMatrix)[jmax][kmax]) {
*outMatrix = malloc(imax*sizeof(**outMatrix));
double (*matrix)[jmax][kmax] = *outMatrix; //avoid having to write (*outMatrix)[i][j][k] everywhere
... //as above
}
This function would need to be called like this:
int imax = ..., jmax = ..., kmax = ...;
double (*myMatrix)[jmax][kmax];
foo(imax, jmax, kmax, &myMatrix);
That way you get full type checking on the inner two dimension sizes even though they are runtime values.
Note: This was intended to be a comment but it got too long, until it turned into a proper answer.
You can't use a single chunk of memory without performing some calculations.
Note that the beginning of each row is marked by the formula
// row_begin is the memory address of the row at index row_idx
row_begin = row_idx * jmax * kmax
And then, each column depends on where the row starts:
// column_begin is the memory address of the column
// at index column_idx of the row starting at row_begin
column_begin = row_begin + column_idx * kmax
Which, using absolute addresses (relative to the matrix pointer, of course) translates to:
column_begin = (row_idx * jmax * kmax) + column_idx * kmax
Finally, getting the k-index of an element is very straightforward, following the previous rule this could turn in an infinite recursion:
// element address = row_address + column_address + element_k_index
element_k_idx = column_begin + element_k_idx
Which translates to
element_k_idx = (row_idx * jmax * kmax) + column_idx * kmax + element_k_idx
This works for me:
void foo(int imax, int jmax, int kmax)
{
// Allocate memory for all the numbers.
// Think of this as (imax*jmax) number of memory chunks,
// with each chunk containing kmax doubles.
double* data_0 = malloc(imax*jmax*kmax*sizeof(double));
// Allocate memory for the previus dimension of pointers.
// This of this as imax number of memory chunks,
// with each chunk containing jmax double*.
double** data_1 = malloc(imax*jmax*sizeof(double*));
// Allocate memory for the previus dimension of pointers.
double*** data_2 = malloc(imax*sizeof(double**));
for (int i = 0; i < imax; i++)
{
data_2[i] = &data_1[i*jmax];
for (int j = 0; j < jmax; j++)
{
data_1[i*jmax+j] = &data_0[(i*jmax+j)*kmax];
}
}
// That is the matrix.
double ***matrix = data_2;
for (int i = 0; i < imax; i++)
{
for (int j = 0; j < jmax; j++)
{
for (int k = 0; k < kmax; k++)
{
matrix[i][j][k] = i+j+k;
}
}
}
for (int i = 0; i < imax; i++)
{
for (int j = 0; j < jmax; j++)
{
for (int k = 0; k < kmax; k++)
{
printf("%lf ", matrix[i][j][k]);
}
printf("\n");
}
}
// Deallocate memory
free(data_2);
free(data_1);
free(data_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
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;
}
[...]
}