c - Border values in table overwrite neighbours -


i writing c program, in try dynamically allocate 2-dim array (or array of arrays.) after table allocated try iterate on it, throws error illegal memory access , creates coredump.

after investigation i've found out curious thing: the array experiment 4x4, when set array[0][3] = 123; sets both [0][3] , [1][0] positions 123. same thing happens if assign array[1][0] = 123;, sets both [0][3] , [1][0] rightside value. similar assignment done "border values", [2][0] , [1][3]. guess must wrong allocation, can't figure out. pretty sure way dynamically allocate multi-dim arrays , bit of research confirmed it. here code (i know should sssce can't provide shorter , still show problem):

typedef struct {     int rows;     int columns;     double **data; } matrix;   matrix* allocatematrix(int inputrows, int inputcolumns) {     matrix *matrixpointer = calloc(1, sizeof(matrix));     matrixpointer->rows = inputrows;     matrixpointer->columns = inputcolumns;     #ifdef double         matrixpointer->data = calloc(inputrows, sizeof(double*));     #else         matrixpointer->data = calloc(inputrows, sizeof(float*));     #endif     if (matrixpointer->data == null) {         printf("error - inputrows value appears wrong.");         return null;     }      int i, j;     (i = 0; < inputrows; i++) {     #ifdef double         matrixpointer->data[i] = calloc(inputcolumns, sizeof(double));     #else         matrixpointer->data[i] = calloc(inputcolumns, sizeof(float));     #endif         if (matrixpointer->data[i] == null) {             printf("error - inputcolumns value appears wrong.");             return null;         }     }     matrixpointer->data[2][0] = 123;    //test code;      return matrixpointer; } 

and code see contents of such created array:

matrix *lol = allocatematrix(4, 4);      int i, j;     (i = 0; < lol->rows; i++)             (j = 0; j < lol->columns; j++)                 printf("%f ", lol->data[i][j]); 

is memory allocation wrong, or maybe other issue fail see. grateful suggestions or help. thank in advance.

typedef struct {     int rows;     int columns;     double **data; } matrix; 

this culprit. double macrodefinition supposed enable double precision through code, when flag not set code still allocated double** data, causing possible segmentation faults. correct code in case should like:

typedef struct {     int rows;     int columns;     #ifdef double         double **data;     #else         float **data;     #endif } matrix; 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -