为什么我的数组在将其传递给另一个函数后会持有垃圾值/ segfaulting?

问题描述 投票:2回答:1

我有一个函数mallocs数组保存值编码。在将值编码到整数数组之后,该数组本身通过引用传递(至少理论上是这样)。但是,当我编译函数时,我得到了垃圾值,所以我开始在各处抛出print语句,看看发生了什么。在调用第二个函数并传递数组之后,我意识到print语句是segfaulting,这对我来说很奇怪。

主要功能:

void    top_left_justify(char **pieces)
{
    int i;
    int j;
    int count;
    int *values; //array to be passed

    i = 0;
    if (!(values = (int *)malloc(sizeof(int) * 4)))
        return ;
    while (pieces[i] != 0)
    {
        j = 0;
        count = 0;
        while (pieces[i][j])
        {
            printf("count = %d\n", count);
            if (pieces[i][j] == '#')
                values[count++] = j;
            j++;
        }
        printf("encoded indexes are: %d, %d, %d, %d\n", values[0], 
values[1], values[2], values[3]); //test printout shows me it works here
        top_left_helper(&values, pieces[i]); //PASS BY REFERENCE??
        i++;
    }
}

但是,在它传递给这个函数之后:

void    top_left_helper(int **values, char *pieces)
{
    int i;
    int j;

    i = 0;
    j = 0;
    printf("value of values[0] = %d\n", *values[0]); //prints correct value
    printf("value of values[0] = %d\n", *values[1]); //segfaults
    left_helper(&*values);
    top_helper(&*values);
    while (i < 16)
        pieces[i++] = '.';
    while (j < 4)
        pieces[*values[j++]] = '#';
}

它在第二份印刷声明中有段落错误。除了误解如何通过引用和内存传递参数之外,我无法真正看到对此的解释。请说清楚。

编辑:经过一些测试,似乎我通过递增指针而不是数组访问来打印出值,我能够正确访问要打印的值。但这对我来说没有任何意义,为什么数组访问不起作用。 (在第二个函数中添加了以下行)

printf("value of values[0] = %d\n", **values);
*values = *values + 1;
printf("value of values[1] = %d\n", **values);
*values = *values + 1;
printf("value of values[2] = %d\n", **values);
*values = *values + 1;
printf("value of values[3] = %d\n", **values);
c arrays pointers malloc pass-by-reference
1个回答
2
投票

这不符合你的想法:

*values[1]

[]的优先级高于*,因此首先将values作为数组进行索引,然后取消引用它返回的值。但是你传递给这个函数的是一个指向变量的指针,该变量也是一个指针。所以values[1]没有意义。你逃脱*values[0],因为它与**values相同你想要的是:

(*values)[1]

但是,除非您需要修改vaules本身,例如在其上使用realloc,否则您无需传递其地址。只需将它作为int *传递给pieces[i]

void    top_left_helper(int *values, char *pieces)
{
    int i;
    int j;

    i = 0;
    j = 0;
    printf("value of values[0] = %d\n", values[0]);
    printf("value of values[0] = %d\n", values[1]);
    left_helper(values);    // probably need to change left_helper the same way
    top_helper(values);     // and also top_helper
    while (i < 16)
        pieces[i++] = '.';
    while (j < 4)
        pieces[values[j++]] = '#';
}

然后相应地更改呼叫:

top_left_helper(values, pieces[i]);
© www.soinside.com 2019 - 2024. All rights reserved.