0
今天我正在與我的實驗室任務一起尋找C語言中最接近的一對點。 我很清楚如何將結構數組發送到函數,但由於某種原因數組沒有反映它在main()函數中的變化。 由於我的代碼很雜亂,我創建了一個較小的代碼來理解錯誤。 以下是代碼:作爲參數傳遞的結構數組沒有反映變化
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
int y;
};
void fun(struct node *);
int main()
{
struct node *arr = (struct node *)malloc(2 * sizeof(struct node));
arr[0].x = 1;
arr[0].y = 2;
printf("%d %d\n", arr[0].x, arr[0].y);
fun(arr);
printf("%d %d\n", arr[0].x, arr[0].y);
return 0;
}
struct node *fun2()
{
struct node *tmp = (struct node *)malloc(2 * sizeof(struct node));
tmp[0].x = 3;
tmp[0].y = 4;
return tmp;
}
void fun(struct node *arr)
{
arr = fun2();
}
輸出
1 2
1 2
但對於以下代碼ARR陣列反映變化
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
int y;
};
void fun(struct node *);
int main()
{
struct node *arr = (struct node *)malloc(2 * sizeof(struct node));
arr[0].x = 1;
arr[0].y = 2;
printf("%d %d\n", arr[0].x, arr[0].y);
fun(arr);
printf("%d %d\n", arr[0].x, arr[0].y);
return 0;
}
struct node *fun2()
{
struct node *tmp = (struct node *)malloc(2 * sizeof(struct node));
tmp[0].x = 3;
tmp[0].y = 4;
return tmp;
}
void fun(struct node *arr)
{
// arr = fun2();
arr[0].x = 3;
arr[0].y = 4;
}
輸出
1 2
3 4
誰能ħ那幫我一下?
我剛剛明白了。由於main()中的arr和fun()中的arr指向版本2中的相同內存位置,因此它在版本1中不會更改,而fun()中的arr將其指向的內存位置更改爲其他位置。這對我來說太愚蠢了。感謝您的回覆。 – user74571