So I have the following function. The function takes a target int ** double pointer and copies a source array to it.
void copyMatrix(int ** target, int m, int n, int source[m][n])
{
int i,j;
target = (int **) malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
target[i] = (int *)malloc(n * sizeof(int));
for(i=0; i < m; i++){
for(j=0; j < n; j++){
target[i][j] = source[i][j];
}
}
printf("%d ", target[i][j]);
}
When i call printf after the for loops, i get a segfault, but if i call printf inside the for loops, it prints target[i][j] correctly. Why is this? I'm tearing my hair out over this...
iandjto be outside the loop?**target, so it becomes***target. And then use*target = ...when allocating. You're currently trying to modify the (double) pointer itself, not the value it points to.targetoutside thecopyMatrixfunction, or return it instead (and don't pass it). Since you have to free it outside the function as it's currently written, you better makecopyMatrixbehave likemallocand friends.