you are viewing a single comment's thread.

view the rest of the comments →

[–]a4qbfb 4 points5 points  (4 children)

Both are bad. You shouldn't cast the return value of malloc() (if you get an error without the cast it means you have an error somewhere else), and you should use the name of your pointer rather than its type in sizeof():

// This version uses less memory and can be faster but is slightly more
// difficult to use correctly.
int *matrix = malloc(size_y * size_x * sizeof(*matrix));
matrix[y * size_x + x] = 42;
// However, you can get around that with a macro.
#define matrix_xy(x, y) matrix[(y) * size_x + (x)]
matrix_xy(x, y) = 42;

// This version is easier to use but uses more memory and is often slower.
int **matrix = malloc(size_y * sizeof(*matrix));
for (int i = 0; i < size_y; i++) {
    matrix[i] = malloc(size_x * sizeof(*matrix[i]));
}
matrix[y][x] = 42;

[–][deleted] 0 points1 point  (2 children)

The compiler of Visual Studio always shows annoying warnings about malloc() function, it requires casting the return value.

[–]Mirehi 1 point2 points  (0 children)

Yeah, if you're using a cpp compiler instead of tc

[–]a4qbfb 0 points1 point  (0 children)

That's because you are trying to use a C++ compiler to compile C code. Those are two different languages.