在c中返回到数组的前一个成员

时间:2016-04-24 19:27:28

标签: arrays indexing

我的作业需要帮助。 我需要构建一个函数来计算数组中成员的总和。 我有一个4X4阵列,我需要计算从第一行开始说成员的总和。 对于来自该行的给定数量的成员,我需要为该行的每个组合组合执行此操作,并检查它是否与用户给我的总和相匹配。 如果行是1 2 3 4。 我需要检查(1 + 2 + 3 + 4),(2 + 3 + 4),(3 + 4),(1),(2),(3),(4) 我知道怎么检查(1)(2)(3)(4) 问题是,一旦我到达第一个总和(1 + 2 + 3 + 4)的末尾,我不知道如何在不使用静态变量的情况下返回到开始求和(2 + 3 + 4)的索引。 我的代码是这样的:

bool row_sum(int length,int sum, int mat[N][N])
{
int temp_sum=0, i=0, j=0, cnt1=0;
while (i<N)
{
    while(j<N)
    {
        cnt1++;
        temp_sum += mat[i][j];
        if ((temp_sum==sum) && (cnt1==length))
        {
            return 1;
        }
        else if (temp_sum<sum)
        {
            j++;
            continue;
            }
        else if (temp_sum>sum)
        {
            if (j==N-1)
            {
                temp_sum=0;
                cnt1=0;
                j=N;
                break;
            }
            else
            {
            temp_sum=0;
            j=(cnt1-j);
            cnt1=0;
            }
        }
        else if ((temp_sum<sum) && (cnt1=length))
        {
            temp_sum=0;
            j=(cnt1-j);
            cnt1=0;
        }
    }
i++;
}
     return 0;
}

我希望我很清楚......很难描述这个问题。 谢谢, 阿迪。

1 个答案:

答案 0 :(得分:0)

数组作为元素序列(char,int,...)存储在内存中,请参阅How is the array stored in memory?

您可以使用指针访问数组的元素(请参阅指针算术 https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html)或使用下标直接寻址,请参阅此{{ 3}}

     0    1    2    3

0    a    b    c    d

1    e    f    g    h

2    i    j    k    l

3    m    n    o    p

所以,如果你想得到这封信,那就是&#39; k&#39;在上面的char数组中使用char c = array[2][2];,如果你想收到这封信,请使用char c = array[2][0];。使用{{1}}