#include <stdlib.h>
#include <stdio.h>
int **a; // global matrix.
int main(void){
int dim = 100;
int size_x = dim; /* X_dimension */
int size_y = dim; /* Y_dimension */
/* allocate storage for an array of pointers */
a = malloc(size_x * sizeof(int *));
/* for each pointer, allocate storage for an array of ints */
for (int i=0; i < size_x; i++) {
a[i] = malloc(size_y * sizeof(int));
}
for(int i =0; i < size_x; i++)
for(int j=0; j < size_y;j++)
/* now for each pointer, free its array of ints */
for (int i = 0; i < size_y; i++) {
free(a[i]);
}
/* now free the array of pointers */
free(a);
return 0;
}
i receive the following compiler errors using either gcc or g++:
13: error: invalid conversion from void* to int**
17: error: invalid conversion from void* to int**
How to fix it,please ?
(2) i have the code
1 2 3 4 5 6 7 8 9 10 11 12
#include <stdlib.h>
#include <stdio.h>
#include <vector.h>
int main(void){
/*
...code which determines the dim variable...
*/
vector<vector<string> >mat(dim, vector<string>(dim)); // matrix mat
return 0;
}
i want the matrix mat to be a global matrix. What i am thinking is to use the (1) code for that. However, i would like to ask how i could do this with vector?
#include <stdlib.h>
#include <stdio.h>
int **a; // global matrix.
int main(void){
int dim = 100;
int size_x = dim; /* X_dimension */
int size_y = dim; /* Y_dimension */
/* allocate storage for an array of pointers */
a = newint*[size_x];
/* for each pointer, allocate storage for an array of ints */
for (int i=0; i < size_x; i++) {
a[i] = newint[size_y];
}
for(int i =0; i < size_x; i++)
for(int j=0; j < size_y; j++)
printf("back to C\n");
/* now for each pointer, free its array of ints */
for (int i = 0; i < size_y; i++) {
delete[] a[i];
}
/* now free the array of pointers */
delete[] a;
return 0;
}
You should never use malloc-free is C++. Instead use new-delete.
And always use a std::vector<> rather than allocating the memory yourself. It is much safe because you don't need to remember to free the memory yourself.