我有這個功能:
void changes_equation_order(double** system, unsigned int qty) {
double aux[100];
//first print
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
printf("%.1lf ", system[i][j]);
if(i == 0)
aux[j] = system[i][j];
}
printf("\n");
}
remove_line(system, 0, qty);
printf("\nReordering the matrix: \n");
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
if(i == qty- 1) {
system[i][j] = aux[j];
}
printf("%.1lf ", system[i][j]);
}
printf("\n");
}
printf("\Second print: \n");
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
printf("%.1lf ", system[i][j]);
}
printf("\n");
}
}
它接收一個矩陣,行和列帶有 qty 值,因此,在示例中,系統是:
0 3 2
4 0 2
2 3 0
qty 等于 3。
當我第一次列印時,矩陣具有正確的值,所以它給了我
0 3 2
4 0 2
2 3 0
當我列印第二個(重新排序列印)時,它會重新排列矩陣值并列印給我:
4.0 0.0 2.0
2.0 3.0 0.0
0.0 3.0 2.0
這是正確的,但是當我立即列印矩陣時,它會產生這個:
4.0 0.0 2.0
0.0 3.0 2.0
0.0 3.0 2.0
為什么會這樣?
此外,這是 remove_line 函式:
void remove_line(double** system, int row, unsigned int qty){
qty--;
free(system[row]);
while(row < qty) {
system[row] = system[row 1];
row ;
}
}
非常感謝你的幫助!
uj5u.com熱心網友回復:
它發生,因為system[1]和system[2]執行后,都指向同一個記憶體remove_line。換句話說,當你改變時,例如system[2][0]它也會改變system[1][0]。它們是相同的記憶。
為了用一個例子來解釋它,假設system[n]當你呼叫時指標有這些值changes_equation_order
system[0] = 0x1000;
system[1] = 0x2000;
system[2] = 0x3000;
然后在執行后remove_line(system, 0, qty);的值將是
system[0] = 0x2000;
system[1] = 0x3000;
system[2] = 0x3000;
如您所見system[1],system[2]現在指向相同的記憶體。
第一次列印看起來不錯,因為您system[1]在執行之前列印了該行
if(i == qty- 1) {
system[i][j] = aux[j];
}
您正在更改system[2]行的位置(但也是system[1]行,因為它們是相同的)。
我不確定你想在 remove_line 函式中做什么,所以我不能給你建議。然而,一個建議......
使用單獨的回圈來列印和修改矩陣!我知道這會給你一些額外的回圈,但你的代碼會更容易理解。
例如,而不是:
printf("\nReordering the matrix: \n");
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
if(i == qty- 1) {
system[i][j] = aux[j];
}
printf("%.1lf ", system[i][j]);
}
printf("\n");
}
使用多個回圈 - 就像
printf("\nPrint before reestablish of last row: \n");
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
printf("%.1lf ", system[i][j]);
}
printf("\n");
}
// Reestablish last row
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
if(i == qty- 1) {
system[i][j] = aux[j];
}
}
}
printf("\nPrint after reestablish of last row: \n");
for(int i = 0; i < qty; i ) {
for(int j = 0; j < qty; j ) {
printf("%.1lf ", system[i][j]);
}
printf("\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322579.html
上一篇:為什么С忽略if陳述句?
