這樣做是否安全?函式完成后區域變數mat會被銷毀嗎?這會在節目后期multiply()產生影響嗎?mat4main()
在矩陣.h
typedef struct Matrix
{
double **entries;
int rows;
int cols;
} Matrix;
在 matrix.c 中
int check_dimensions_for_multiplication(Matrix *m1, Matrix *m2)
{
if (m1->cols == m2->rows)
return 1;
return 0;
}
Matrix *matrix_create(int rows, int cols)
{
Matrix *matrix = malloc(sizeof(Matrix));
matrix->rows = rows;
matrix->cols = cols;
matrix->entries = malloc(rows * sizeof(double *));
for (int i = 0; i < rows; i )
{
matrix->entries[i] = malloc(cols * sizeof(double));
}
return matrix;
}
Matrix *multiply(Matrix *m1, Matrix *m2)
{
if (check_dimensions_for_multiplication(m1, m2))
{
Matrix *mat = matrix_create(m1->rows, m2->cols);
for (int i = 0; i < m1->rows; i )
{
for (int j = 0; j < m2->cols; j )
{
mat->entries[i][j] = m1->entries[i][j] * m2->entries[i][j];
}
}
return mat;
}
else
{
printf("Dimension mismatch multiply: %dx%d %dx%d\n", m1->rows, m1->cols, m2->rows, m2->cols);
exit(1);
}
}
在main.c:
Matrix *mat4 = multiply(mat2, mat1);
uj5u.com熱心網友回復:
malloc不,在函式終止后不應銷毀在堆中分配的變數。
int * someInteger = malloc(sizeof(int));
此代碼將在稱為堆的位置分配一些記憶體(可能是 4 個位元組),堆是作業系統為您的程式提供的空間。在堆中分配的記憶體是一塊永久的記憶體,它會在程式的整個生命周期中傳播,除非您free使用那個特定的指標。
只有分配的區域變數被銷毀,因為它們存盤在堆疊中。
如果您想了解有關區域變數和堆疊的更多資訊,可以查看此網站
http://users.cecs.anu.edu.au/~Matthew.James/engn3213-2002/notes/upnode25.html#:~:text=The stack is used for,variables in the% 20stack frame。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512694.html
標籤:C矩阵
上一篇:Realloc不復制舊值
下一篇:在c中減去后提取數字
