/*i am doing in main function*/
int main(void)
{
//allocating memory
double** p = malloc(ROWS * sizeof(double*));
int i, j;
for (i = 0; i < ROWS; i++)
p[i] = malloc(COLS * sizeof(double));
// set every array element as 1
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++)
p[i][j] = 1;
//print array element
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
printf("%f ", p[i][j]);
printf("\n");
}
make5(ROWS, COLS, p);
//here why this is changed???
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
printf("%f ", p[i][j]);
printf("\n");
}
return 0;
}
/* and changing value in below function */
int make5(int r, int c, double **d)
{
int i, j;
/*changing value of received array*/
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
d[i][j] = 5;
}
}
return 0;
}
You passed the pointer by value - but that's just a pointer. That says where the memory containing the individual values is. Your make5
function doesn't actually change the value of the parameter (d
) at all - that would be something like:
d = malloc(...);
Pass-by-value refers to changes to the argument value (p
in this case) being simply copied to the parameter (d
). Further changes to the parameter are not seen by the caller of the function. And that's fine, because there are no changes to the parameter. Instead, your function changes the contents of the memory that d
refers to. That's the same memory that p
refers to, so you see the changes when you print the values after calling the function. (In this case there are actually two levels of indirection, as the value of p
says where further pointers are, but the principle is the same.)
Suppose I have my street address written on a piece of paper (p
). I photocopy that piece of paper, and give it to you, calling the copy d
. I don't care about anything you do to the piece of paper - but if you visit my house and paint the door a different colour, I will see that, because I've still got the street address of my house on my piece of paper. The piece of paper doesn't contain my house - it just tells me how to get to my house. Likewise, the pointer doesn't contain all the individual values - it just tells you how to get to them.
See more on this question at Stackoverflow