繁体   English   中英

将指针数组传递给函数

[英]Passing an array of pointers to a struct to a function

我有一个函数,其中声明了指向结构的指针数组

void functionA(argument1, argument2) {
   ...
   struct1 *point[2];
   ...

   functionB(*point, ...) // Call the function ?
}

// Declare the function ?
void functionB(struct1 *point[], ...) {


}

我需要将此数组*point[2]传递给另一个函数,例如functionB,在该函数中,我需要基于point[0]point[1]进行一些操作,正确的方法是什么?

当我打电话的functionBfunctionAfunctionB(*point, ...)我越来越不兼容的指针类型的错误,而当我调用它像functionB(*point[], ...)我收到]令牌之前的预期表达的错误。

您的函数调用错误。 functionB期望其参数为struct1 **类型,但您传递的是struct1 *类型的参数。 函数调用应该是

functionB(point, ...);  

您应该知道,按照C规则,当将数组传递给函数时,数组会衰减到指向其第一个元素的指针。 函数调用中的point会衰减,衰减后的类型struct1 **

这是一种实现方法:

void functionA(argument1, argument2) {
   ...
   struct1 *point[2];
   ...

   functionB(point, ...) // Call the function ?
}

// Declare the function ?
void functionB(struct1 ** point, ...) {

  // Use point[1] and point[2] here
}

当您需要将数组发送给函数时,只需要将该数组的基地址(即名称)发送给该函数,然后使用指向该类型的指针来接收它。 这个规则适用于每种数据类型,无论是int还是struct


所以,你可以做

void functionA(argument1, argument2) {
   ...
   struct1 *point[2];
   ...

   functionB(point, ...) // Sending base address of array point
}

// Recieve it this way
void functionB(struct1 *point[], ...) {

// Or
void functionB(struct1 **point, ...) {

函数functionB被声明为具有struct1 *point[]类型的第一个参数

void functionB(struct1 *point[], ...) {


}

并且数组point具有相同类型的元素。

因此,您只需要使用数组名称作为函数调用的参数即可

functionB(point, ...) // Call the function ?

请考虑将声明为数组的参数附加到指向其元素的指针。

因此,此函数声明

void functionB(struct1 *point[], ...);

void functionB(struct1 **point, ...);

等价并声明相同的一个函数。

另一方面,表达式中使用的数组指示符将转换为指向其第一个元素的指针。 因此,用作参数的表达式point转换为struct1 **类型的指针,即它与函数参数根据其声明所期望的值完全对应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM