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

查看:119
本文介绍了用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天全站免登陆