This is confusing:
D=(int*)malloc(sizeof(int*)*col);
D=(int*)CopieD;
You call malloc
to allocate some memory and assign the pointer to D
. You then immediately overwrite that pointer with the address of CopieD, thus losing your reference to that dynamically allocated memory.
Do you want D
to simply point to CopieD
, or do you want D
to be a copy of CopieD
?
If you simply want D
to point to CopieD
, then do the following:
int (*D)[col] = CopieD; // assumes int CopieD[lig][col]
int (*D)[col]
declares D
as a pointer to a col
-element array of int
; it is not an array, despite the presence of [col]
in the declaration. The expression CopieD
"decays" from type "lig
-element array of col
-element array of int
" to type "pointer to col
-element array of int
".
If you want D
to be a copy of CopieD
, then you would do:
int (*D)[col] = malloc( sizeof *D * lig ); // notice no cast, sizeof operand
memcpy( CopieD, D, sizeof *D * lig );
In either case, your display code would be written as
for(i=0; i<lig;i++)
{
for(j=0; j<col;j++){
printf("%d ", D[i][j] );
}
printf("\n");
The subscript operator []
works just the same on pointers as it does on array objects.
A note on the malloc
call:
As of the 1989 standard1, you do not need to cast the return value of malloc
2, and under C89/90 compilers it can potentially mask a bug. Recommended practice in C is to not cast the result of malloc
.
Instead of passing a type to sizeof
, we pass the expression *D
, which will have type int [cols]
. So sizeof *D
is the same as sizeof (int [cols])
; multplying that result by lig
gives us the total size of the array in bytes.
1. Prior to the 1989 standard, malloc
returned a value of type char *
, so a cast was required if you wanted to assign it to a different pointer type. Values of type void *
can be assigned to other pointer types (and vice versa) without an explicit cast.
2. In C, anyway; C++ requires the cast, but you shouldn't use malloc
in C++ code.