如何使函数返回正确的值?

时间:2017-01-14 20:35:28

标签: c arrays function

我编写了这个函数,它找到了数组中最长的序列,并且它应该返回长度以及序列开始的位置。

如何使*开始指向遇到的第一个(最长)序列?

"name": "DineSafe",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "parse": "1.9",
    "parse-react": "^0.5.2",
    "react": "15.4.0",
    "react-native": "^0.40.0",
    "react-native-animatable": "^1.1.0",
    "react-native-cacheable-image": "^1.4.3",
    "react-native-global-props": "^1.0.7",
    "react-native-image-crop-picker": "^0.11.1",
    "react-native-keyboard-spacer": "^0.3.1",
    "react-native-progress": "^3.1.0",
    "react-native-svg": "4.4.0",
    "react-native-triangle": "0.0.6"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-jest": "17.0.2",
    "babel-preset-react-native": "1.9.0",
    "jest": "17.0.3",
    "jest-react-native": "17.0.3",
    "react-test-renderer": "15.3.2"
  }

2 个答案:

答案 0 :(得分:1)

  

如何让*begin指向遇到的第一大序列?

要使*begin指向某个内容,*begin必须是指针,begin必须是指向指针的指针。

传递来电者int *begin的地址,因此longestSequence()应该收到char**

int longestSequence(int a[], int n ,int** begin) { 
  ...
       *begin = &a[i];
  ...
  return length;
}

// call
int *call_begin = NULL;
int length = longestSequence(a, n, &call_begin);

答案 1 :(得分:0)

要修改此功能中的*begin指针,您需要提供自己的地址

我的意思是你需要一个int **而不是简单的指针

新原型将是:int longestSequences(int a[], int n, int **begin)

int longestSequences(int a[], int n, int **begin)
    {
         for(i=0; i<n; i++)
         {
            if(a[i+1]==a[i])
            {
                length++;
                if(length>oldlength)
                {
                    oldlength=length;
                    *begin= &(tab + i); //(which is equivalent to &tab[i]
                }
            }
           else
            {
                oldlength=length;
                length=1;
            }
    }