S
somenath
The output of the following program is not clear to me.
#include<stdio.h>
#include<stdlib.h>
void Get_Array_Memory(int (*ar)[5])
{
int i =0;
int (*temp)[5];
printf("\nar before assignment = %p\n",(void *)ar); //print 3
temp= malloc(5);
if ( temp ) {
printf("\ntemp = %p\n",(void *)temp);
ar = temp;
printf("\nar after asignment = %p\n",(void *)ar); //print 4
for ( i =0;i < 5; i++ ) {
*(*ar + i ) = i;
}
}
}
int main(void)
{
int (*arr)[5];
int a[5] ;
int i=0;
arr = &a;
printf("\narr in main = %p\n",(void *)arr); //print 1
Get_Array_Memory(arr);
printf("\narr in main after function call = %p\n",(void *)arr); //print 2
for ( i =0;i < 5; i++ ) {
printf(" val of ar = %d\n",i ,*(*arr + i)); //print 5
}
return 0;
}
The output
++++++++++++++++++++++
arr in main = 0x28ac44
ar before assignment = 0x28ac44
temp = 0x800482c0
ar after asignment = 0x800482c0
arr in main after function call = 0x28ac44
val of ar = 0
val of ar = 1
val of ar = 2
val of ar = 3
val of ar = 4
++++++++++++++++++++++++++++++
It is clear that ar in Get_Array_Memory assigned to new address 0x800482c0which is different than 0x28ac44 passed from main. Then how the values assigned in Get_Array_Memory is retained and the same values are getting printed in main? Is it just by chance I am getting the output in main?
#include<stdio.h>
#include<stdlib.h>
void Get_Array_Memory(int (*ar)[5])
{
int i =0;
int (*temp)[5];
printf("\nar before assignment = %p\n",(void *)ar); //print 3
temp= malloc(5);
if ( temp ) {
printf("\ntemp = %p\n",(void *)temp);
ar = temp;
printf("\nar after asignment = %p\n",(void *)ar); //print 4
for ( i =0;i < 5; i++ ) {
*(*ar + i ) = i;
}
}
}
int main(void)
{
int (*arr)[5];
int a[5] ;
int i=0;
arr = &a;
printf("\narr in main = %p\n",(void *)arr); //print 1
Get_Array_Memory(arr);
printf("\narr in main after function call = %p\n",(void *)arr); //print 2
for ( i =0;i < 5; i++ ) {
printf(" val of ar = %d\n",i ,*(*arr + i)); //print 5
}
return 0;
}
The output
++++++++++++++++++++++
arr in main = 0x28ac44
ar before assignment = 0x28ac44
temp = 0x800482c0
ar after asignment = 0x800482c0
arr in main after function call = 0x28ac44
val of ar = 0
val of ar = 1
val of ar = 2
val of ar = 3
val of ar = 4
++++++++++++++++++++++++++++++
It is clear that ar in Get_Array_Memory assigned to new address 0x800482c0which is different than 0x28ac44 passed from main. Then how the values assigned in Get_Array_Memory is retained and the same values are getting printed in main? Is it just by chance I am getting the output in main?