cfor-loopnested-loopspointer-arithmetic

Modification pgm fill 2-D Array using a pointer and it doesn't work


Initial pgm

void assign( int **mat, int n, int m ) {
int **p = mat;
int **p_end = p + n;
for ( ; p < p_end; ++p ) {
  int *q = *p;
  int *q_end = q + m;
  for ( ; q < q_end; ++q ) {
     printf( "Give an integer: " );
     scanf( "%d", q );
  }
 }
}

modified pgm

void assign_V2( int **mat, int n, int m) {   
int **p = mat;  
for ( ; p < p + n; ++p )   
{
 int *q = *p;  
 for ( ; q < q + m; ++q ) 
  {         
    printf( "Give an integer: " );         
    scanf( "%d", q );         
  }  
 }   
}

Introduce p+n and q+m in the for loop. Execution: it keeps asking me "Give an integer". Address incrementation problem ? Thanks.


Solution

  • This for loop

    for ( ; p < p + n; ++p ) 
    

    is incorrect because p is always less than p + n (of course provided that n keeps a positive number) within the for loop by the value n * sizeof( int * ) or strictly speacking the code invokes undefined behavior.

    Opposite to the second code snippet in the first code snippet the value of p_end is initially fixed and does not depend on the value of p within the for loop.

    int **p_end = p + n;
    for ( ; p < p_end; ++p ) {