c - 如何通过 C 中的函数引用来传递数组?

标签 c arrays struct

我是一名 C 语言初学者。

我有以下代码:

int main()

{

struct* Array[malloc(10*sizeOf(struct)];
  /* I then fill the struct. (int num,float points)
   * I then want to pass this array that I've filled up to a sortList function,
   * which then outputs the sorted array back to main().
   *
   * Then I want to output the array as: "number, points" */
}

struct struct
{
int number;
float points;
}

void sortList()
{
  /*sort Array, then return sorted array*/
}

How would I pass the array and then back?

任何链接或建议都非常有帮助。

最佳答案

How to pass an array by reference ...?

当数组a传递给函数foo(a)时,它是实际参数。在 C 中,当将数组传递给函数时,而不是将整个数组传递给 foo(),表达式 a 会转换为第一个元素的地址数组的。

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. ... C11dr §6.3.2.1 3

因此,foo() 被赋予一个 int * 类型的地址。我们假设该值为 1234

在函数 void foo(int *fa) 中,形参 fa 的值为 1234 >.

从调用者的角度来看,这是引用传递,因为 afoo() 影响,并且函数收到了“引用”。从函数的角度来看,这是按值传递,因为 fa 获取转换后的 a 的副本。在 C 中,当人们说 C 不通过引用传递任何内容时,通常会提到第二种观点。在这两种情况下,fa 都是 int * 而不是数组。

foo() 在变量 fa 中具有 maina 的地址。因此,代码 fa[0] = 456 设置的值在 foo() 完成后仍然可见。

void foo(int *fa) {
  fa[0] = 456;
}

int main(void) {
  int a[5];
  a[0] = 123;
  printf("%d\n", a[0]); // prints 123
  foo(a);
  printf("%d\n", a[0]); // prints 456
  return 0;
}
<小时/>

我使用了一个简单的int数组来解释事情。然而原始代码还有其他问题。以下是有关如何分配内存的想法。

//  struct* Array[malloc(10*sizeOf(struct)];
struct ok12type* ok12Array = malloc(sizeof *ok12Array * 10);
....
// Do stuff with ok12Array
...
free(ok12Array);
ok12Array = NULL;
// Do _not_ do stuff with ok12Array

关于c - 如何通过 C 中的函数引用来传递数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35210505/

相关文章:

c - C 中的重复 GtkWidget

复制结构的组件会删除同一结构的另一个组件

c - 嵌入式系统编程的松耦合模式

c - 为结构成员赋值

c# - 如何找到数组的模式(最频繁的元素)?

ios - 当 tableview 结束时添加更多数据

JavaScript 检查数组越界

c - 指向结构的指针成员

c - 将变量分配给结构中的属性

c++ - readv(), writev(), WSARecv(), WSASend()