Edit3: Added Example.
Edit2: So, because I am new to coding in general and because of the current comments,I need to ask, would it be better if I posted the entire code as a comment? (around 90 lines)
So, I have been playing around with dynamic memory allocation and I have a 2D board, witch fills with '.'. Then I import the board in a function, witch checks for available cells (cell with '.'==available). It compiles ok, but when I run it I get
segmentation fault
Here's the code for the board malloc
**board = (char**) malloc(x_input*sizeof(char*));
for(i = 0; i <x_input; i++){
board[i] = (char*) malloc(y_input*sizeof(char));
}
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
Here's the Function
int checker(int x_axis, int y_axis, char **board){
if (board[x_axis][y_axis] == '.'){
return 1;
} else {
return 2;
}
}
And here's the only time(so far) that I call the function
Edit: x_replacement and y_replacement are assigned random values through a rand function
do{
board[x_replacement][y_replacement] = '$';
} while(checker(x_replacement, y_replacement, board) == 2);
EX:
const int MAX_X = 40;
const int MAX_Y = 40;
const int MIN_X = 20;
const int MIN_Y = 20;
int x_input, y_input;
int main(void){
char **board;
int i, j, k, obstacles, enemies, choice;
do{
printf("Enter board size. (Must be between (%d, %d) and (%d, %d))\n:", MIN_X, MIN_Y, MAX_X, MAX_Y);
scanf("%d%d", &x_input, &y_input);
}while ((x_input <= MIN_X && x_input >= MAX_X) && (y_input <= MIN_Y && y_input >= MAX_Y));
*board = malloc(sizeof(char[x_input][y_input]));
assert(*board != NULL);
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
return 0;
}
I approached this from a different perspective, thanks to Ludin's and Some Programmer Dude's links so the result, witch works is the following:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void arr_alloc (size_t x, size_t y, char(**board)[x][y])
{
*board= malloc( sizeof(char[x][y]) );
assert(*board!= NULL);
}
void arr_fill (size_t x, size_t y, char board[x][y])
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
array[i][j] = '.';
}
}
}
void arr_print (size_t x, size_t y, char board[x][y])
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int main (void)
{
int x,y;
char (*board)[x][y];
printf("enter dimentions: \n");
scanf("%d%d", &x, &y);
arr_alloc(x, y, &board);
arr_fill(x, y, *board);
arr_print(x, y, *board);
free(board);
return 0;
}
Related
I'm coding a game "Tic Tac Toe"
and I ask each player to enter their next move in two different functions,
then I save their moves in 2D array, and save this array in another 2d array in the main function.
but when I print the array it changes the char symbol when the second player enters his next move.
PS: it's a char array.
here is my code
char player1(char board[N][N], int n)
{
int k, l;
print_player_turn(1);
scanf("%d%d", &k, &l);
board[k - 1][l - 1] = 'X';
print_board(board, n);
return board;
}
char player2(char board[N][N], int n)
{
int k, l;
print_player_turn(2);
scanf("%d%d", &k, &l);
board[k - 1][l - 1] = 'O';
print_board(board, n);
return board;
}
int main()
{
char board[N][N];
int n;
print_welcome();
print_enter_board_size();
scanf("%d", &n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
board[i][j] = '_';
print_board(board, n);
char* ptr = board;
while (isFull(board,n)==0)
{
board[0][0] = player1(board, n);
if (XloseGeneral(board, n) == 1)
{
print_winner(2);
return 0;
}
board[0][0] = player2(board, n);
if (OloseGeneral(board, n) == 1)
{
print_winner(1);
return 0;
}
}
print_tie();
}
I would suggest you expand the scope of the 2D array 'board' such that it is accessible to all methods including player 1 and player 2, instead of passing it as a parameter.
This way you can make sure that the modification is being done on the same variable, and that no reinitialisation happens, which results in loss of the previous entry.
Arrays are passed to functions by reference. Which means, a pointer to the array is passed to the function. Hence, any modifications done to the array inside the function will reflect the caller (the main method in your case). So, make your function void as it doesn't need to return anything, and remove the return statement from it.
As others have said you don't need to return the board, you can just pass the pointer to the board. Here's a short example based on your code:
#include <stdio.h>
#include <stdlib.h>
void player1(char **board);
void player2(char **board);
void print_board(char **board, int n);
void player1(char **board){
int k, l;
fprintf(stderr, "Player 1, enter grid position:\n");
scanf("%d%d", &k, &l);
board[k - 1][l - 1] = 'X';
}
void player2(char **board){
int k, l;
fprintf(stderr, "Player 2, enter grid position:\n");
scanf("%d%d", &k, &l);
board[k - 1][l - 1] = 'O';
}
void print_board(char **board, int n){
for (int i = 0; i < n; i++){
for( int j = 0; j < n; j++ ){
fprintf(stdout, "%c ", board[i][j]);
}
fprintf(stdout, "\n");
}
}
int main()
{
int n;
char **board;
fprintf(stdout, "Type in the board size:\n");
scanf("%d", &n);
// allocate memory for the board
board = (char **) malloc(n * sizeof(char*));
for (int i = 0; i < n; i++){
board[i] = (char *)malloc(n * sizeof(char));
for (int j = 0; j < n; j++){
board[i][j] = '_';
}
}
print_board(board, n);
player1(board);
player2(board);
print_board(board, n);
return 0;
}
I am working on a problem where I have to transpose a matrix. I am passing the address of the original matrix, but once I execute the function it does not change!
I have tried to add a * infront of matrix in the transpose function, thinking that it will be pointing to the whole 2d array, but it did not work.
#include<stdio.h>
#include <stdlib.h>
void transpose(int *r,int *c, int **matrix);
void printMatrix(int r,int c, int **matrix){
for(int i=0;i<r;i++){
for(int j=0;j<c;j++)
printf("%2d ",matrix[i][j]);
printf("\n");
}
}
int main() {
int **matrix;
int r =3;
int c =2;
matrix = (int**) malloc(r*sizeof(int*));
for(int i=0;i<r;i++)
matrix[i] = (int*) malloc(c*sizeof(int));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++)
matrix[i][j] = (3*i+2*j)%8+1;
}
printf("Before transpose:\n");
printMatrix(r,c,matrix);
transpose(&r, &c ,matrix);
printMatrix(r,c,matrix);
return 0;
}
void transpose(int *r,int *c, int **matrix){
int newR = *c;
int newC = *r;
int **newMatrix;
newMatrix = (int**) malloc(newR*(sizeof(int*)));
for(int i=0; i<newR;i++)
newMatrix[i] = (int*) malloc(newC*(sizeof(int)));
for(int i=0; i<newR; i++)
for(int j=0;j<newC;j++)
newMatrix[i][j] = matrix[j][i];
*c = newC;
*r = newR;
matrix = (int**) malloc((*r)*sizeof(int*));
for(int i=0;i<*r;i++)
matrix[i] = (int*) malloc((*c)*sizeof(int));
for(int i=0; i<newR; i++){
for(int j=0;j<newC;j++){
matrix[i][j] = newMatrix[i][j];
}
printf("\n");
}
}
I have this matrix
1 3
4 6
7 1
and want to get
1 4 7
3 6 1
however I am getting
1 3 0
1 4 0
It looks like all you forgot to do was actually use the transposed matrix. All I did was change the function signature and return the matrix you had already allocated and manipulated, and I got the output you were looking for.
#include <stdio.h>
#include <stdlib.h>
int** transpose(int *r,int *c, int **matrix);
void printMatrix(int r, int c, int **matrix) {
for (size_t i = 0; i < r; ++i){
for (size_t j = 0; j < c; ++j) {
printf("%2d ",matrix[i][j]);
}
printf("\n");
}
}
int main()
{
int r = 3;
int c = 2;
int **matrix = calloc(sizeof(int*), r);
for (size_t i = 0; i < r; ++i) {
matrix[i] = calloc(sizeof(int), c);
}
for (size_t i = 0; i < r; ++i) {
for (size_t j = 0; j < c; ++j) {
matrix[i][j] = (3 * i + 2 * j) % 8 + 1;
}
}
printf("Before transpose:\n");
printMatrix(r, c, matrix);
int** newMatrix = transpose(&r, &c ,matrix);
printMatrix(r, c, newMatrix);
return EXIT_SUCCESS;
}
int** transpose(int *r, int *c, int **matrix) {
int newR = *c;
int newC = *r;
int **newMatrix = calloc((sizeof(int*)), newR);
for (size_t i = 0; i < newR; ++i) {
newMatrix[i] = (int*) malloc(newC*(sizeof(int)));
}
for (size_t i = 0; i < newR; ++i) {
for (size_t j = 0; j < newC; ++j) {
newMatrix[i][j] = matrix[j][i];
}
}
*c = newC;
*r = newR;
matrix = calloc(sizeof(int*), *r);
for (size_t i = 0; i < *r; ++i) {
matrix[i] = calloc(sizeof(int), *c);
}
for (size_t i = 0; i < newR; ++i) {
for (size_t j = 0; j < newC; ++j) {
matrix[i][j] = newMatrix[i][j];
}
printf("\n");
}
return newMatrix;
}
Output:
1 4 7
3 6 1
I changed a few things, especially because I prefer using calloc over malloc, since it zeroes out the newly-allocated memory, and there is a dedicated parameter for the size of the requested memory, which I think semantically is a better idea.
As a side note, you don't have to cast the result of malloc in C. I tend to feel more strongly about that than other people, I think, because code noise, especially when you're working in C is one of the worst things you can do to yourself. This is a pretty good example of that, since all I did was reformat your code and the answer was right there. Don't be stingy with the whitespace, either; it really does make a difference.
Anyways, I hope this helped somewhat, even if you literally had basically everything done.
#include<stdio.h>
#include <stdlib.h>
void transpose(int *r,int *c, int ***matrix);
void printMatrix(int r,int c, int **matrix){
int i=0,j=0;
for(i=0;i<r;i++){
for(j=0;j<c;j++)
printf("%2d ",matrix[i][j]);
printf("\n");
}
}
int main() {
int **matrix;
int r =3;
int c =2;
int i=0,j=0;
matrix = (int**) malloc(r*sizeof(int*));
for(i=0;i<r;i++)
matrix[i] = (int*) malloc(c*sizeof(int));
for(i=0;i<r;i++){
for(j=0;j<c;j++)
matrix[i][j] = (3*i+2*j)%8+1;
}
printf("Before transpose:\n");
printMatrix(r,c,matrix);
transpose(&r, &c, &matrix);
printMatrix(r,c,matrix);
return 0;
}
void transpose(int *r,int *c, int ***matrix){
int newR = *c;
int newC = *r;
int **newMatrix;
int i=0,j=0;
newMatrix = (int**) malloc(newR*(sizeof(int*)));
for(i=0; i<newR;i++)
newMatrix[i] = (int*) malloc(newC*(sizeof(int)));
for(i=0; i<newR; i++)
for(j=0;j<newC;j++) {
newMatrix[i][j] = (*matrix)[j][i];
}
*c = newC;
*r = newR;
// free matrix..
*matrix = newMatrix;
/*matrix = (int**) malloc((*r)*sizeof(int*));
for(i=0;i<*r;i++)
matrix[i] = (int*) malloc((*c)*sizeof(int));
for(i=0; i<newR; i++){
for(j=0;j<newC;j++){
matrix[i][j] = newMatrix[i][j];
}
printf("\n");
}*/
}
This is a sample implementation of KD-tree.
Where I first take number of dimensions, number of points, number of clusters to be formed. Bi-partition function calculates centroid, dimension which has max variance. Now based on the max dimensions mean I start splitting the points. This program works fine when input is (dimensions-2,points-20,clusters-4). But does not work for (dimensions-2,points-20,clusters-8). When I debug the program it gives proper output.But when I run the program it stops working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stdbool.h>
int *gendata(int num);
void bipartition_fn(int dimensions,int nodes,int i0, int im, int *data,int *cluster_size,int *cluster_start, int *cluster_bdry, int *cluster_centroid);
void kdtree_fn(int dimensions, int nodes, int k, int *data,int *k_cluster_size,int **k_cluster_centroid,int *k_cluster_start,int **k_cluster_bdry );
int main()
{
int dimensions,nodes,i,k,j;
printf("enter the number of dimensions");
scanf("%d",&dimensions);
printf("enter the total number of elements in multiples of dimensions");
scanf("%d", &nodes);
printf("enter number of clusters");
scanf("%d",&k);
int *data;
int *k_cluster_size;
int **k_cluster_centroid;
int *k_cluster_start;
int **k_cluster_bdry;
data = gendata(nodes); /*dynamic array generation for data points*/
k_cluster_bdry=(int **)malloc(k*sizeof(int *));
for(i=0;i<(2*k-2);i++)
*(k_cluster_bdry+i)=(int *)malloc(2*dimensions*sizeof(int));
k_cluster_centroid=(int **)malloc(k*sizeof(int *));
for(i=0;i<(2*k-2);i++)
*(k_cluster_centroid+i)=(int *)malloc(dimensions*sizeof(int));
k_cluster_size=malloc((2*k-2)*sizeof(int));
k_cluster_start = malloc((2*k-2)*sizeof(int));
/*calling the kdtree function*/
kdtree_fn(dimensions, nodes, k, data, k_cluster_size, k_cluster_centroid, k_cluster_start, k_cluster_bdry);
/*printing the cluster size */
printf("cluster size \n");
for(i=k-2; i<(2*k - 2); i++){
printf("%d ", k_cluster_size[i]);
}
free(data);
free(k_cluster_bdry);
free(k_cluster_centroid);
free(k_cluster_size);
free(k_cluster_start);
return 0;
}
void kdtree_fn(int dimensions, int nodes, int k, int *data,int *k_cluster_size,int **k_cluster_centroid,int *k_cluster_start,int **k_cluster_bdry){
int i,j,d0,dm,x,m=0,l,n=0,check=1,s,temp=0;
d0 = 0, dm =nodes ;
int *cluster_size, *cluster_start;
int *cluster_bdry;
int *cluster_centroid;
int *query;
int *res;
query = (int *)malloc(sizeof(int)*dimensions);
res = (int *)malloc(sizeof(int)*dimensions);
cluster_centroid = (int*)malloc(dimensions*sizeof(int));
cluster_bdry = (int*)malloc(4*dimensions*sizeof(int));
cluster_size=(int*)malloc(2*sizeof(int));
cluster_start = (int*)malloc(2*sizeof(int));
/* iterating k-1 times to form k clusters */
for(x=0 ; x<k-1; x++){
bipartition_fn(dimensions, nodes, d0, dm, data, cluster_size, cluster_start, cluster_bdry, cluster_centroid);
for( i=0;i<dimensions; i++){
k_cluster_centroid[x][i] = cluster_centroid[i];
}
for( i=0;i<2; i++){
k_cluster_size[m] = cluster_size[i];
k_cluster_start[m] = cluster_start[i];
m++;
}
int p=0,r=0;
while(p<2){
l=0;
i=0;
while(i<2*dimensions){
k_cluster_bdry[temp][l] = cluster_bdry[r];
l++;
i++;
r++;
}
temp++;
p++;
}
s = pow(2,check);
if(x == 0 ||(x%(s-2)) == 0){
d0 =0;
nodes = k_cluster_size[n];
check++;
n++;
}
else{
d0 = d0+k_cluster_size[n-1];
nodes = k_cluster_size[n];
n++;
}
}
free(cluster_bdry);
free(cluster_centroid);
free(cluster_size);
free(cluster_start);
}
/*Each bipartition function gives 2 clusters*/
void bipartition_fn(int dimensions,int nodes,int d0, int dm, int *data,int *cluster_size,int *cluster_start, int *cluster_bdry, int *cluster_centroid){
int i,j,x,k;
int node = nodes/dimensions;
int sum,min,max;
int *cluster_assign;
cluster_assign = malloc(nodes*sizeof(int));
int *assign;
assign= (int *)malloc(node*sizeof(int));
// printf("nodes: %d \n", nodes);
/*calculate centroid and boundaries*/
i=0;
j=d0;
while(i<dimensions){
sum=0;
while(j<(d0+nodes)){
sum = sum+data[j];
j = j+dimensions;
}
cluster_centroid[i] = sum/node;
i = i+1;
j=d0+i;
}
/* Calculate variance of each dimension and find dimension with maximum variance*/
int var[dimensions],g,h;
h=d0;
g=0;
while(g<dimensions){
sum = 0;
while(h<(d0+nodes)){
sum = sum +((cluster_centroid[g] - data[h])*(cluster_centroid[g] - data[h]));
h=h+dimensions;
}
var[g] = sum/node;
g=g+1;
h=(d0+g);
}
int large = var[0];
int max_dimension =0;
int p;
for(p=0; p<dimensions; p++){
if(var[p]>large){
large = var[p];
max_dimension = p;
}
}
/* find mean of maximum variance*/
int mean = cluster_centroid[max_dimension];
//printf("mean %d \n",mean);
i=d0+max_dimension;
x=0;
while(i<(d0+nodes)){
if(data[i] < mean){
assign[x]=0;
}
else{
assign[x]=1;
}
x++;
i= i+dimensions;
}
/* Rearranging the points based on mean points lesser than mean goes to left and greater than mean goes to right*/
x=0;
int count=0;
int y=0;
for(i=0; i<node; i++){
if(assign[y] == 0){
count++;
for(j=dimensions*i; j<dimensions*(i+1); j++){
cluster_assign[x] = data[d0+j];
x++;
}
}
y++;
}
cluster_size[0] = count*dimensions;
cluster_start[0]= d0;
count=0;
y=0;
for(i=0; i<node; i++){
if(assign[y]!=0){
count++;
for(j=dimensions*i; j<dimensions*(i+1); j++){
cluster_assign[x] = data[d0+j];
x++;
}
}
y++;
}
cluster_size[1] = count*dimensions;
cluster_start[1]= d0+cluster_size[0];
int temp1,temp2;
x=0;
p=0;
while(p<2){
j=cluster_start[p];
i=0;
while(i<dimensions){
min=data[j];
max=data[j];
temp1=cluster_start[p];
temp2=cluster_size[p];
while(j < temp1+temp2){
if(data[j]<min)
min = data[j];
if(data[j]>max)
max= data[j];
j = j+dimensions;
}
cluster_bdry[x]=min;
x=x+1;
cluster_bdry[x]=max;
x=x+1;
i = i+1;
j=temp1+i;
}
p++;
}
/*printf("bou");
for(i=0; i<4*dimensions; i++){
printf("%d ",cluster_bdry[i]);
} */
free(cluster_assign);
free(assign);
}
/*Initialize data array*/
int *gendata(int num)
{
int *ptr = (int *)malloc(sizeof(int)*num);
int j = 0;
if(ptr != NULL)
{
for(j = 0; j < num; j++)
{
ptr[j] = -50 + rand()%101;
}
}
return ptr;
}
I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).
I wrote this simple piece of code to dynamically allocate a 4-dimensional array:
#include <stdlib.h>
#include <stdio.h>
int**** alloc() {
int i,j,k;
int ****matrix;
int x,y,z,n_pairs;
x= 62;
y= 45;
z= 28;
n_pairs = 4;
matrix = (int ****) malloc(x*sizeof(int***));
for (i=0; i<x; i++) {
matrix[i] = (int ***) malloc(y*sizeof(int**));
if(matrix[i]==NULL)
return NULL;
for (j=0; j<y; j++) {
matrix[i][j] = (int **) malloc(z*sizeof(int*));
if (matrix[i][j] == NULL)
return NULL;
for (k=0; k<n_pairs; k++) {
matrix[i][j][k] = (int *)calloc(n_pairs,sizeof(int));
if (matrix[i][j][k] == NULL)
return NULL;
}
}
}
return matrix;
}
void freeMatrix(int ****m) {
int i,j,k;
int x,y,z;
x= 62;
y= 45;
z= 28;
for(i=0; i<x; i++) {
for(j=0; j<y; j++) {
for(k=0; k<z; k++)
free(m[i][j][k]);
free(m[i][j]);
}
free(m[i]);
}
free(m);
}
int main() {
int i,j,k,h;
int ****m = NULL;
m = alloc();
for(i=0;i<62;i++)
for(j=0;j<45;j++)
for(k=0;k<28;k++)
for(h=0;h<4;h++)
printf("%d\t",m[i][j][k][h]);
system("pause");
return 0;
}
the problem is that I this code results in an Access Violation when I try to execute it.
Isn't it the correct way to allocate/free a multidimensional array? If yes, then what is the problem?
One problem is here:
for (k=0; k<n_pairs; k++) { //<----- This should read `k<z'
matrix[i][j][k] = (int *)calloc(n_pairs,sizeof(int));
You probably meant to loop to z, not to n_pairs.
if u make a matrix the correct way is to allocate all the memory u need, then dived it up.
for 2.dim
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
int ** matrix;
int rows = 10;
int colums =10;
matrix = (int**)malloc(rows*sizeof(int*));
matrix[0] = (int*)malloc(rows*colums*sizeof(int));
for(i =1; i<rows;i++)
matrix[i] = &matrix[i-1][colums];
free(matrix[0]);
free(matrix);
return 0;
}
this is for having a continues memory area for the matrix. this can be faster