-
Segmentation Fault
Hey all,
I had previous question that was expertly answered today, and now I have another issue. I am trying to display the values I entered into a dynamic 2-dimensional array, but when my code gets to the display loop, I get a segmentation fault. My code so far is below.
Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
main() {
int i, j;
double *CellPtr;
//values to hold row & col size for array & mem size needed
int col, row, Doubles;
printf("\nEnter the number of columns desired for your array \n");
scanf("%d", &col);
printf("\nEnter the number of rows desired for your array \n");
scanf("%d", &row);
Doubles = col * row;
//declaring the array
double **ArrayPtr;
ArrayPtr = malloc(row * sizeof(double *));
for(i = 0; i < row; i++)
ArrayPtr[i] = malloc(col * sizeof(double));
//filling the array with the requested values
for(i = 0; i < row; i++)
for(j = 0; j < col; j++) {
*ArrayPtr = (int) i * 100 + j;
ArrayPtr++;
}
//THIS IS GIVING ME THE PROBLEM
for(i = 0; i < row; i++)
for(j = 0; j < col; j++)
printf("%d\n", ArrayPtr[i][j]);
}
I hope it's OK to include the whole program; it's pretty small.
If anyone could let me know why I'm getting the segmentation fault (or if there's a glaring, horrific error in my display code logic), I'd really appreciate it.
Thanks in advance!
-
You moved your ArrayPtr hither and yon throughout the thickets of your doubly-subscripted array. Now: how are you going to get it back?
(EDIT: And for bonus fun: who says your doubly-subscripted array is all stored in order?)
-
> printf("%d\n", ArrayPtr[i][j]
You should have used this notation to write to the array.
You also need to look up how to use printf as well - %d is not for doubles.