为什么我的传递引用代码在C中不起作用?

np8igboo  于 2023-06-05  发布在  其他
关注(0)|答案(2)|浏览(161)

有人能指出为什么我在这段代码中得到一个错误,应该怎么修复?这似乎对其他人有效。谢谢你!
我正在尝试编写一个数组引用传递的例子

  1. #include <stdio.h>
  2. void set_array(int array[4]);
  3. void set_int(int x);
  4. int main(void) {
  5. int a = 10;
  6. int b[4] = { 0, 1, 2, 3 };
  7. set_int(a);
  8. set_array(b);
  9. printf("%d %d\n", a, b[0]);
  10. }
  11. void set_array(int array[4]) {
  12. array[0] = 22;
  13. }
  14. void set_int(int x) {
  15. x = 22;
  16. }
ncecgwcz

ncecgwcz1#

  1. x = 22;
  2. }

为什么这不起作用?
您提供的代码未按预期工作,因为您是通过值而不是通过引用向函数set_arrayset_int传递参数。在C中,函数参数是通过值传递的,这意味着复制参数,并且在函数中对参数进行的任何修改都不会影响原始变量。
set_array函数中,当你修改array[0]时,它会影响原始数组,因为C中的数组是通过引用传递的(数组名充当指向第一个元素的指针)。但是,在set_int函数中,您正在修改局部变量x,它是main函数中a变量的副本。因此,修改不影响原始变量。
要解决此问题,可以修改函数以接受指向变量的指针。下面是代码的更新版本,它演示了指针的正确用法:

  1. #include <stdio.h>
  2. void set_array(int* array);
  3. void set_int(int* x);
  4. int main(void)
  5. {
  6. int a = 10;
  7. int b[4] = { 0, 1, 2, 3 };
  8. set_int(&a);
  9. set_array(b);
  10. printf("%d %d\n", a, b[0]);
  11. }
  12. void set_array(int* array)
  13. {
  14. array[0] = 22;
  15. }
  16. void set_int(int* x)
  17. {
  18. *x = 22;
  19. }
展开查看全部
pobjuy32

pobjuy322#

当你传递一个参数给一个函数时,你实际上是在传递一个值的副本。所以当你这么做的时候

  1. void set_int(int x) {
  2. x = 22;
  3. }
  4. int main(int argc, char** argv) {
  5. int a = 20;
  6. set_int(22);
  7. printf("%d\n", a);
  8. }

你实际上做的是复制a的值,并把它放到x中,现在你要做的是变量,a和x. x被设置为22,你从函数中返回,C会自动从内存中删除x。
为了得到正确的变量,你可以使用一个整数(技术上是无符号的长整型,但对于我们的目的是整型)值的指针,它表示内存中存储另一个值的点。

  1. int main(int arc, char** argv) {
  2. int a = 20;
  3. int* b = &a;
  4. }

在该示例中,B是指向a的类型“int指针”。我们可以更新set_int()函数来“解引用”我们的新指针值。

  1. void set_int(int* x) {
  2. // Dereference out int* with the * operator
  3. // y is out original integer a at the same spot in memory
  4. int y = *x;
  5. // Because we are using a we can now set it to out value of 22
  6. y = 22;
  7. }
  8. int main(int arc, char** argv) {
  9. int a = 20;
  10. int* b = &a;
  11. set_int(b);
  12. // This should print 22
  13. printf("%d\n", a);
  14. return 0;
  15. }

请注意,set_int()是这样写的,以帮助理解指针是如何工作的,通常你会把它压缩成一行:

  1. void set_int(int* x) {
  2. *x = 22;
  3. }

当然,我们也可以压缩我们的调用:

  1. int main(int argc, char** argv) {
  2. int a = 20;
  3. set_int(&a);
  4. printf("%d\n", a);
  5. return 0;
  6. }
展开查看全部

相关问题