当您将指针作为参数传递给 C 中的函数时,copy的指针已完成。因此,更改指针的值在该函数之外没有任何影响。但是,改变内存中的值引用者指针将在任何地方生效,如你所愿。对于您的情况,您需要执行以下操作:
void func(int arr[], int *s, int *l, int n){
// sorting code..
// l = &arr[n-1]; WRONG - these change the value of the pointer,
//s = &arr[0];\ without changing the value of the memory they reference
*l = arr[n-1]; // CORRECT - changes the value at the referenced memory
*s = arr[0];
printf("%d %d\n",*l,*s);
}
当然,您使用指针的方式main
也是不正确的;它们未初始化,可能会导致分段错误。由于似乎没有理由使用实际的int*
变数超常int
那里的变量,我们可以采取另一种方法“通过引用”传递它们:
int main(void){
int arr[] = {1,2,9,3,58,21,4};
// int *s, *l; WRONG - we don't need pointers, we need to pass regular ints
int s, l;
int size = 7;
// Get the address of our variables with the address-of (&) operator
// This effectively creates int* variables out of our int variables
func(arr, &s, &l,size);
printf("%d %d\n",*l,*s);
}
请注意,此处的术语“通过引用”在该短语的真正意义上并不正确,因为您仍然收到copy与变量关联的地址。大多数语言通过消除这种区别并只允许访问变量及其值来提供真正的引用功能,而复制在程序员的视线之外。您可以将其视为“通过参考l
and s
inside main
”,从某种意义上说,它们的值可能会因被调用的函数而改变。