首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从函数A返回数组,然后函数B获取此数组

如何从函数A返回数组,然后函数B获取此数组
EN

Stack Overflow用户
提问于 2019-01-04 04:28:31
回答 2查看 78关注 0票数 0

在我的main函数中有两个函数。

我试着用指针来解决这个问题,但是作为一个初学者,使用它是非常复杂的。

int main(){
  int *p;

  p = function_A();
  function_B(p);

  return 0; 
}

int function_A(){
  static int myArray[3];
  myArray[0] = 11;
  myArray[1] = 22;
  myArray[2] = 33;

  return myArray;
}

int function_B(int *myPointer){
  // Here I just want to print my array I've got from function_A() to the 
  // console

  printf("%d", *myPointer)
  return 0;
}

function_A应该返回一个数组,而function_B应该接受这个数组。

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2019-01-04 04:46:11

有些问题你的编译器已经告诉你了。首先,您应该在调用函数之前定义它们,或者至少向前声明它们。

其次,要返回数组,需要返回指向该数组第一个元素的指针,即返回类型是int *而不是int

第三,正如FredK所指出的,当您只接收一个指针时,您没有机会确定它所指向的数组中有多少个元素。你可以用一个特定值结束数组,比如0,或者你也需要返回数组的大小。

请参阅对您的程序所做的以下调整:

int* function_A(int *size){
    static int myArray[3];
    myArray[0] = 11;
    myArray[1] = 22;
    myArray[2] = 33;

    if (size) {
        *size = 3;
    }
    return myArray;
}

void function_B(int *myPointer, int size){
    for (int i=0; i<size; i++) {
        printf("%d\n", myPointer[i]);
    }
}

int main(){
    int *p;

    int size=0;
    p = function_A(&size);
    function_B(p,size);

    return 0;
}
票数 2
EN

Stack Overflow用户

发布于 2019-01-04 20:40:36

如果数组的大小确实是3(或其他较小的固定值),那么您可以简单地使用structs作为值,如下所示:

struct ints3 {
  int values[3];
  // if needed, can add other fields
}

int main(){
  struct ints3 ints;

  ints = function_A();
  function_B(&ints);

  return 0; 
}

// note about function_A signature: void is important,
// because in C empty () means function can take any arguments...
struct ints3 function_A(void) {
  // use C designated initialiser syntax to create struct value,
  // and return it directly
  return (struct ints3){ .values = { 11, 22, 33 } };
}

int function_B(const struct ints3 *ints) {
  // pass struct as const pointer to avoid copy,
  // though difference to just passing a value in this case is insignificant

  // could use for loop, see other answers, but it's just 3 values, so:
  printf("%d %d %d\n", ints->values[0], ints->values[1], ints->values[2]);
  return 0; // does this function really need return value?
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54029347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档