为取消引用的双指针

时间:2016-06-10 09:19:14

标签: c pointers segmentation-fault

我编写了这个函数来计算uint32数组奇数或偶数索引的平均值:

void average_uint32_t(uint32_t * begin, uint32_t *end,
            uint8_t skip, uint32_t **result){

    //safety check
    if(begin == end || begin > end) {
        printf("begin and end pointer does not belong to an array\n");
        *result = 0; //set pointer to null
        return;
    }

    uint64_t sum = 0;
    uint32_t count = 0;

    while(begin <= end) {
        sum += *begin;
        count++;
        printf("count=%d,value=%d,sum=%lu\n", count, *begin, sum);
        begin += skip;
    }

    **result = ((uint32_t)(sum/count)); //segmentation fault here
    printf("result=%d\n", **result);
}

我测试这样的功能:

//BUFF_SIZE = 8
uint32_t buffer[BUFF_SIZE] = {0,1,2,3,4,5,6,7};

uint32_t * average = 0; //memory to get result back

//even indices => 0,2,4,6
average_uint32_t(buffer, buffer + BUFF_SIZE - 1, 2, &average);
printf("average of even elements = %d\n", *average);

//odd indices => 1,3,5,7
average_uint32_t(buffer + 1, buffer + BUFF_SIZE, 2, &average);
printf("average of odd elements = %d\n", *average);

但是当将结果分配到平均值时,程序会遇到分段错误(正如我在功能代码中所评论的那样)。这是输出:

count=1,value=0,sum=0
count=2,value=2,sum=2
count=3,value=4,sum=6
count=4,value=6,sum=12
Signal: SIGSEGV (Segmentation fault)

我做错了什么?我想普通函数的单个指针可以解决问题吗?但为什么双指针不起作用?

2 个答案:

答案 0 :(得分:1)

那是因为uint32_t *average没有指向有效的内存区域。

试试这个:

uint32_t uiAverage = 0;
uint32_t *average = &uiAverage;

更好的方法是使用double代替uint_32_t,因为平均值可以是浮点数。因此,如果您打算使用double,那么您还需要更改行

**result = ((uint32_t)(sum/count));

**result = ((double)sum/(double)count));

答案 1 :(得分:1)

您将average定义为空指针。取消引用空指针是Undefined Behavior,在大多数Unix风格中,它会导致分段违规。

您必须使用单个指针指向实际变量,或者如果您想使用双指针,则平均必须指向现有变量。