问题
I have dynamically created a matrix using calloc in the usual way:
int **matrix;
int dim,r;
scanf("%d",&dim);
matrix=(int **)calloc(dim, sizeof(int *));
for(r=0; r<dim; r++)
{
matrix[r]=(int *)calloc(dim, sizeof(int));
}
Now if I wanted to create a function to just print the elements of this matrix, I should write something like:
void stampmatrix(int **matrix, int dim)
{
int r=0, c=0;
for(r=0; r<dim; r++)
{
printf("(");
for(c=0;c<dim;c++)
{
printf(" %d , ",matrix[r][c]);
}
printf(")");
}
}
And this works fine. Now I add this line to the previous function
`...`
matrix[r][c]=1;
printf(" %d , ",matrix[r][c]);
...
If i call this function in my main function, stampmatrix(matrix,dim) once i run the program, the compiler should create a copy of my matrix, fill it with 1, and then print them, and then return to my main function without changing the actual matrix. But if I do this and then i check in my main function the values of my matrix elements, they are changed to 1. In class i was told that if I pass values to a function, the program creates a copy of the values, works with them and then cancel the copy, so I need to pass addresses to a function in order to actually change the contents of my variables in my main function. Why in this case it doesn't work, and changes my matrix values? It's because I still pass pointers to the function stampmatrix? I really don't understand. Shouldn't the function be something like:
void stampfunction(int dim, int ***matrix)
Or it's because i used a void function? Thanks for the attention!
回答1:
Remember, in this program (I assume), all code shares the same heap (memory), and pointers are kind of like signposts, to that heap.
What the method
void stampmatrix(int **matrix, int dim)
does is like when you give a person a number, dim
, and physical map to, say, all the signposts to apples in a grid.
So yes, you passed in by value directions to the matrix - you gave a person a copy of your apple-signpost-map.
The other thing you did is that matrix[r][c]
implicitly dereferences the pointer - or, the method is saying to follow the apple-signpost-map directions all the way to point (r, c) in this grid.
So when you say `matrix[r][c] = 1', you're saying to make sure there's only one apple at (r, c) when you leave. That's why the value at matrix[r][c] changed.
来源:https://stackoverflow.com/questions/38422813/passing-pointers-matrix-to-a-function-in-c