Pete Pete - 24 days ago 4x
C Question

Precise Syntax for Accessing Elements in a 2D Array - by Pointer?

I'm a CS student working on a homework assignment, and I need help with a C syntax issue. Yesterday in class, my professor said, "an int** pointer is a pointer to a 2D int array." This blew my mind.

Turns out, we have to write a C program which reads an int matrix from a file, then do operations on that matrix. For example, "matrix1.txt" might look like this:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

...for a 5x3 matrix. I get the dimensions of the matrix from another file, which is a problem I've already solved. But the point is I have to dynamically allocate the matrix array using variables.

Here's my issue: Its easy enough to use an int** pointer to malloc() an Y-by-X array... but what's the syntax to access it? Here's my code:


int main(int argc, char *argv[]){

char *myFile = argv[1];
FILE *targetFile;
targetFile = fopen(myFile, "r");

if (targetFile == NULL)
return -1;
else {
// Successfully opened "matrix1.txt" file
int x, y; // dimensions of the array, learned elsewhere...
int i, j;
char* data = NULL;

int** matrix = (int**)malloc((x*y)*sizeof(int)); // allocate memory for an Y-by-X array

for(i=0; i<y; i++){
for(j=0; j<x; j++){
fscanf(targetFile, "%c ", &data);
matrix[i][j] = atoi(data); // program seg faults here
return 1;

The issue is the "matrix[i][j] = atoi(data);" line; I'm either using the wrong syntax or I haven't initialized the array. I can't tell which - the program seg faults IMMEDIATELY once I hit this line in the GDB debugger.

I'm sure this is a C 101 kind of question... but I post this because I've been reading a lot of different posts on 2D arrays and pointers, yet I can't seem to find an example that fits my precise situation. Can anyone help me out with this?



The syntax used in

matrix[i][j] = atoi(data);

is not incorrect. It's the logic used to allocate memory that is wrong.

One way to allocate memory for the 2D array is:

// Allocate memory for y number of int*s.
int** matrix = malloc(y*sizeof(int*));
for(i=0; i<y; i++)
   // Allocate memory for x number of ints.
   matrix[i] = malloc(x*sizeof(int));
   for(j=0; j<x; j++)
      // Assign to the ints
      matrix[i][j] = <some value>;

For reading the data, use

int data;


fscanf(targetFile, "%d", &data);

Then, the inner loop above can be updated to:

   for(j=0; j<x; j++)
      // Assign to the ints
      fscanf(targetFile, "%d", &data);
      matrix[i][j] = data;

Make sure to add code to release the dynamically allocated memory.

// Free the memory allocated for the ints
for(i=0; i<y; i++)

// Free the memory allocated for the int*s