There is a whole lot of misconceptions here and your teacher does unfortunately not seem to know C very well. You simply can't use a type***
and it doesn't make any sense to use either.
A pointer of the type type***
cannot point at a 3D array of type
. Nor can it point at a 2D array. It cannot point at any array type at all.
Sometimes when using dynamic memory allocation, we allocate an array of type*
, each pointing at the first item in an array. A type**
can then be used to point at the first type*
element, to emulate the syntax of a 2D array with [i][j]
access.
This does however not magically make the array of type*
an array type[]
at the same time. Nor does it magically make type**
an array type[][]
. If someone taught you that, they are confused.
Most of the time, we should not use type**
to emulate a 2D array in the first place, because doing so is horribly inefficient. See Correctly allocating multi-dimensional arrays.
Thus when you attempt ptr3 = Matrix;
, you get a C language constraint violation error by the compiler. Some lax compilers "only" give you a warning, but that doesn't make the code valid C. The type***
cannot be used to point at a 3D array, period.
If you somehow got the correct output in some scenario, that's by luck, since the behavior of your code isn't well-defined. On some system, int
happened to have the same size as the pointer or such.
ptr3 = malloc(sizeof(int)); ptr3 = ...
is senseless, since all that you achieve with the malloc is a memory leak. Because the first thing you do is to overwrite the pointer address to the data you just allocated. I'm not sure why you want to allocate a single int
to begin with.
Getting rid of all misconceptions, you can perhaps salvage the program in the following manner:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int (*iptr)[3];
int imatrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
iptr = imatrix;
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
printf_s("%d ", iptr[i][j]);
}
printf("\n");
}
printf("\n");
float (*fptr)[3];
float fmatrix [3][3] = { {1.0f,2.0f,3.0f},{4.0f,5.0f,6.0f},{7.0f,8.0f,9.0f} };
fptr = fmatrix;
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
printf_s("%.1f ", fptr[i][j]);
}
printf("\n");
}
}