-3

In the C language, In my file Lire.h, I have:

int* D; 

And in the file Lire.c, I have:

  D=(int*)malloc(sizeof(int*)*col);
  D=(int*)CopieD;

  for(i=0; i<lig;i++){
      for(j=0; j<col;j++){
         printf("%d ",*(D+i*col+j));
       }
      printf("\n");
  }

This shows me:

      1 1 1 3 4 1 
      1 2 3 8 2 1 
      1 3 3 5 4 7 
      2 1 4 1 1 4 
      2 2 2 3 9 3 
      2 3 9 1 2 2 
      3 1 8 6 3 5 
      3 2 4 5 8 1 

but its not working well when I put the display blocks in the file main.c

int main(){
for(i=0; i<lig;i++){
    for(j=0; j<col;j++){
        printf("%d ",*(D+i*col+j));
    }
    printf("\n");
}
}

it gives:

      1 1 1 3 855638020 1 
      1 2 4206857 1 1 0 
      2345187 0 1 0 4 7 
      2 1 4 1 1 4 
      2 2 2 3 9 3 
      2 3 9 1 -2146121937 1 
      3 1 -2146122209 1 1 5 
      3 0 0 0 0 0 

????????

1 Answers1

0

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 malloc2, 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.
John Bode
  • 119,563
  • 19
  • 122
  • 198