提问人:Baunuxi02 提问时间:3/10/2022 最后编辑:Vlad from MoscowBaunuxi02 更新时间:3/10/2022 访问量:795
指针在从函数 [duplicate] 返回后为 NULL
Pointers are NULL after returning from a function [duplicate]
问:
我是 C 编程的初学者。当函数返回 main() 时,两个 int 指针返回 NULL,但在函数中它们指向正确的值。你有什么建议吗?
int main(){
int k_attivi=0, n=0, in_game = 0, i, k=0;
int *array_indici = NULL, *array_ingame = NULL;
Player *players = NULL;
players = upload_players(&k, &in_game, &n, &k_attivi, array_indici, array_ingame);
return 0;
}
Player *upload_players(int *k, int *in_game, int *n_tot, int *k_attivi, int* array_indici, int* array_in_game){
FILE *partita = NULL;
Player *players=NULL;
partita = fopen("file.bin", "rb");
if(partita==NULL)
exit (-1);
fread(k, sizeof(int ), 1, partita);
players = calloc(*k, sizeof(Player));
fread(players, sizeof (Player), *k, partita);
fread(in_game, sizeof(int ), 1, partita);
if(*in_game == 1){
fread(n_tot, sizeof(int), 1, partita);
fread(k_attivi, sizeof(int), 1, partita);
array_indici = calloc(*k_attivi, sizeof(int));
fread(array_indici, sizeof(int), *k_attivi, partita);
array_in_game = calloc(*k, sizeof(int));
fread(array_in_game, sizeof(int), *k, partita);
}
fclose(partita);
return players;
}
答:
2赞
Vlad from Moscow
3/10/2022
#1
指针通过值传递给函数。这意味着该函数处理传递的指针值的副本。副本的更改不会影响用作参数表达式的原始指针。
您需要通过指向它们的指针通过引用传递它们。
例如
Player *upload_players(int *k, int *in_game, int *n_tot, int *k_attivi,
int** array_indici, int* array_in_game);
并调用函数
players = upload_players(&k, &in_game, &n, &k_attivi, &array_indici, &array_ingame);
在函数中,您需要取消引用指针才能直接访问原始指针,例如
*array_indici = calloc(*k_attivi, sizeof(int));
为了清楚起见,比较传递的指针,例如在 main 中声明的变量。该变量通过指向它的指针通过引用传递。因此,通过取消引用指向函数的指针来更改函数中的变量将反映在 main 中的原始变量上。同样,您需要通过指向它们的指针将指针传递到通过引用的函数。k
k
k
评论