0

I have code like this:

#include <stdio.h>
#include <stdlib.h>

int main() {
int x=10;
int y=10;

int **data = (int**) malloc(x * sizeof(int));
if(!**data){
    printf("Error");
    return 1;
}
for(int i=0;i<x;i++){
    *(data+i) = (int*) malloc(y * sizeof(int));
    if(!*(data+i)){
        printf("Error");
        return 1;
    }
}

for(int i=0;i<x;i++){
    for(int j=0;j<y;j++){
        data[i][j]=(i+1)*(j+1);
    }
}

for(int i=0;i<x;i++){
    for(int j=0;j<y;j++){
        printf("%3i ",data[i][j]);
    }
    printf("\n");
}


return 0;
}

How can i access points of that array using pointers instead of data[i][j]?

I tried searching for answer but in every example I see people use data[x][y] option, i have to use pointers for accessing each element.

Also is error handling correct in that code?

if(!**data){
    printf("Error");
    return 1;
}

1 Answers1

0

Here's a major problem, especially on 64-bit systems where sizeof(int) != sizeof(int *):

int **data = (int**) malloc(x * sizeof(int));

You allocate x times the size of int, not the size of pointer to int.

There is a good "trick" to always get the correct size, use sizeof *variable_youre_allocating_for. In your case it would be

int **data = malloc(x * sizeof *data);

This works because sizeof *data is done at compile-time, and the compiler knows that *data is of type int * and will use the correct size.

Also notice that I removed the cast, it's not needed in C.

Besides that, your use of the data is correct. Using data[i][j] is perfectly fine, if i and j are valid indexes, and data and data[i] have been properly initialized.

The important part is to remember that for any pointer or array a and index i, the expression a[i] is exactly equal to *(a + i). In fact, the compiler will translate a[i] to *(a + i). So for your pointer data, the expression *(data + i) is exactly equal to data[i]. And the latter is usually easier to read and understand, as well as less to write.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621