在 C 中返回数组? [英] Return Array in C?

查看:16
本文介绍了在 C 中返回数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 C 中返回数组,我对 C 很陌生,所以我可能会犯一些有趣的错误,这里是代码:

I cant return array in c,i am quite new to C so i probably do some kind of funny mistake, here is the code:

#define MAXSIZE 100
int recievedNumbers[MAXSIZE];
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  recievedNumbers = getACOfNumber(256);
  for (int i = 0; i < sizeof(recievedNumbers) / 8; i++) {
    Serial.print(recievedNumbers[i]);
  }
  Serial.println();
}

int* getACOfNumber(int theNumber) {
  bool done = false;
  int i = 0;
  int theArray[100];
  while (!done) {
    if (theNumber % 2 == 0) {
      theNumber = theNumber / 2;
      theArray[i] = 2;
    } else if (theNumber % 3 == 0) {
      theNumber = theNumber / 3;
      theArray[i] = 3;
    }
    else if (theNumber % 5 == 0) {
      theNumber = theNumber / 5;
      theArray[i] = 5;
    }
    else if (theNumber % 7 == 0) {
      theNumber = theNumber / 7;
      theArray[i] = 7;
    } else {
      theArray[i] = theNumber;
      done = true;
    }
    i++;
  }
  return theArray;
}

错误信息:

AC:10: 错误:'int*' 到 'int 的赋值中的类型不兼容[100]'

AC:10: error: incompatible types in assignment of 'int*' to 'int [100]'

在将int*"分配给int"时退出状态 1 不兼容的类型[100]'

exit status 1 incompatible types in assignment of 'int*' to 'int [100]'

推荐答案

不能从表达式赋值给数组:

You can not assign to an array from an expression:

int recievedNumbers[MAXSIZE];
...
recievedNumbers = getACOfNumber(256);

相反:

memcpy(receivedNumbers, getACOfNumber(256), sizeof(receivedNumbers));

注意您正在使用一个生命周期以函数结束的本地数组,更改为

An notice that you are using a local array whose lifetime ends with the function, change to

static int theArray[100];

或者更好

int *theArray = calloc(100, sizeof(*theArray)); /* Zero initializes the array */

不要忘记在最后调用free:

int *temp = getACOfNumber(256);

memcpy(receivedNumbers, temp, sizeof(receivedNumbers));
free(temp);

但是为什么不将原始数组传递给函数呢?:

But why don't you pass the original array to the function?:

getACOfNumber(receivedNumbers);
...
void getACOfNumber(int *theArray) {

这篇关于在 C 中返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆