This question already has an answer here:
- Passing an array as an argument to a function in C 9 answers
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!