Hello,
I've written a C Library to deal with 2D arrays of integers. However I keep getting segmentation errors when I try to use the setArray() or getArray() function, and I'm not sure why. Probably trying to use memory I haven't allocated? Any help would be muchos appreciated.
The code can be viewed at http://www.bath.ac.uk/~jah29/CM10138/ if you find that easier.
2DArray.h
Code:
#ifndef ARRAY_H
#define ARRAY_H
extern int **createArray(int x, int y);
extern int setArray(int **array, int x, int y, int value);
extern int getArray(int **array, int x, int y);
#endif
2DArray.c
Code:
#include "2DArray.h"
static int max_x;
static int max_y;
/* allocates memory for a new array of chosen size */
int **createArray(int x, int y)
{
int **array;
int i = 0;
max_x = x;
max_y = y;
array = malloc(max_x * sizeof(int *));
for(i = 0; i < max_x; i++)
{
array[i] = malloc(max_y * sizeof(int));
}
return &array[0];
}
/* sets the value of a 'cell' in the 2d array,
** returns 0 if successfull, 1 otherwise
*/
int setArray(int **array, int x, int y, int value)
{
if(x > 0 && x < max_x && y > 0 && y < max_y)
{
array[x][y] = value;
return 0;
}
else
{
return 1;
}
}
/* returns the value at specified 'cell', returns 0 if out of bounds */
int getArray(int **array, int x, int y)
{
if(x > 0 && x < max_x && y > 0 && y < max_y)
{
return (int)array[x][y];
}
else
{
return 0;
}
}
arraytest.c
Code:
/* ArrayTest.c */
#include <stdio.h>
#include "2DArray.h"
main()
{
int temp;
int **array1;
int **array2;
array1 = **createArray(10, 5);
printf("Array 10 by 5 created\n");
array2 = **createArray(15, 3);
printf("Array 15 by 3 created\n");
setArray(array1, 5, 3, 100);
/*if (temp != 0)
{
printf("Error array1\n");
}
else
{
printf("Integer set array1\n");
}*/
temp = getArray(array1, 5, 3);
if(temp != 0)
printf("%d at array1 (5, 3)\n", temp);
else
printf("Nothing stored at array1 (5, 3) yet!\n");
setArray(array2, 10, 1, 256);
temp = getArray(array2, 10, 1);
if(temp != 0)
printf("%d at array2 (10, 1)\n", temp);
else
printf("Nothing stored at array2 (10, 1) yet!\n");
temp = getArray(array1, 5, 3);
if(temp != 0)
printf("%d at array1 (5, 3)\n", temp);
else
printf("Nothing stored at array1 (5, 3) yet!\n");
temp = getArray(array2, 10, 1);
if(temp != 0)
printf("%d at array2 (10, 1)\n", temp);
else
printf("Nothing stored at array2 (10, 1) yet!\n");
}
Thanks for your help!
Jack