Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 wothin the for loop.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading