c - 如何让一个函数返回正确的值?

标签 c arrays function

我编写了这个函数来查找数组中最长的序列,它应该返回长度以及序列从哪里开始。

如何让 *begin 指向它遇到的第一个最大(最长)序列?

int longestSequence(int a[], int n ,int* begin)
{
    int oldlength=1,length=1,i,maxvalue=0;
    for(i=0; i<n; i++)
    {
        if(a[i+1]==a[i])
        {
            length++;
            if(length>oldlength)
            {

                oldlength=length;
                *begin=i;

            }
        }
        else
        {
            oldlength=length;
            length=1;
        }

最佳答案

How can I make *begin point to the first largest sequence it encountered?

要使 *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);

关于c - 如何让一个函数返回正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654733/

相关文章:

php - 输入错误内联

javascript - 错误 : "Please use POST request" with Form and Javascript

c - OProfile 警告 'dropping hyperspace sample' 是什么意思?

c - 为什么数组参数的大小与 main 中的大小不同?

c - 每次执行 a.out 时,getpid() 递增 5 或 6

javascript - 用重音排序西里尔文字

php - 在 list.phtml 中显示产品属性 - Magento

c++ - Visual C++ 速成版

c - 为什么这个 C 函数什么都不做?

r - R中这个函数的逻辑有什么问题?