uncertainty in order of execution - any explanation?
I have a piece of code which prints the values and addresses of a 2D array:
Code:
#include<stdio.h>
int main(void)
{
/* declare array[3][4] which is stored contigurously in memory */
int array[3][4]={{1,2,3,4},
{5,6,7,8},
{9,10,11,12}};
int *ptr,i,j;
int nrows=3,ncols=4;
puts("Using array notation...");
for(i=0; i<nrows; i++)
for(j=0; j<ncols; j++)
printf("\narray[%d][%d]=%d",i,j,array[i][j]);
puts("\n\n\nUsing pointer notation...");
/* type cast since ptr is a pointer to int; array is a
constant pointer to an int array[4] */
ptr=(int *)array;
for(i=0; i<nrows; i++)
for(j=0; j<ncols; j++)
printf("\narray[%d][%d]=%d",i,j,*ptr++);
printf("\n\n");
ptr=(int *)array;
for(i=0; i<nrows; i++)
for(j=0; j<ncols; j++)
printf("\n&array[%d][%d]=%u",i,j,ptr++);
printf("\n\n");
/* ptr=(int *)array;
for(i=0; i<nrows; i++)
for(j=0; j<ncols; j++)
printf("\narray[%d][%d]=%d at address %u",i,j,*ptr++,ptr++);*/
ptr=(int *)array;
for(i=0; i<nrows; i++)
for(j=0; j<ncols; j++)
{
printf("\narray[%d][%d]=%d at address %u",i,j,*ptr,ptr);
ptr++;
}
printf("\n\n");
return 0;
}
The commented out region did not give me correct result, which
was obtained after I put the pointer increment out of the printf statement:
Not working...
Code:
printf("\narray[%d][%d]=%d at address %u",i,j,*ptr++,ptr++);*/
Working...
Code:
printf("\narray[%d][%d]=%d at address %u",i,j,*ptr,ptr);
ptr++;
However, it was no program when ptr++ or *ptr++ appear singly in a printf statement as in previous examples. I read something about the order of execution of ptr++ and *ptr++ can be uncertain when they are printed together. Any more insightful explanation is much welcome!!! Or any other things similar to this situation that I should look out for?
Thanks in advance!
Re: uncertainty in order of execution - any explanation?
Code:
printf("\narray[%d][%d]=%d at address %u",i,j,*ptr++,ptr++);*/
When this statement is executed, ptr is incremented after printing the *ptr++ parameter, then incremented again for the ptr++.
Therefore, the second ptr does not have the value expected.
Illiustrated with the following code
Code:
#include<stdio.h>
int xx[] = {11,22,33,44,55,66,77,88,99,38};
int main()
{
int *p,i;
p = xx;
for (i=0; i<5; i++)
{
// display the index, value, address
printf("%d) %d %p \n", i, *p, p);
p++;
}
printf("\n");
p = xx;
for (i=0; i<5; i++)
{
// display the index, value, address
printf("%d) %d %p \n", i, *p++, p++);
}
printf("\n");
}