gpt4 book ai didi

c - 为取消引用的双指针赋值时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:05 25 4
gpt4 key购买 nike

我编写了这个函数来计算 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)

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

最佳答案

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

试试这个:

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

更好的做法是使用 double 而不是 uint_32_t,因为 average 可以是 float 。因此,如果您打算使用 double,那么您还需要更改行

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

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

关于c - 为取消引用的双指针赋值时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37744497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com