gpt4 book ai didi

c - c中for循环的段错误

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

我正在编写一个磁力计采样函数。

它按预期进行循环,其中 samplesPerAxis = 33,MAX_AXES 为 3,MAX 为 999

如您所见,段错误发生在 for 循环完成后,但最终的“end”并未打印出来。

void createSamplingData(){
int i, indexOfValue, numaxis=0, sampling_value ;
printf("%i %i %i\n", magmin[0], magmin[1], magmin[2]);
printf("%i %i %i\n", magmax[0], magmax[1], magmax[2]);

for (numaxis = 0; numaxis < MAX_AXES; numaxis++){
printf("beginAxis: %i\n", numaxis);

sampling_value = magmin[numaxis];
for (i = samplesPerAxis*numaxis ; i < samplesPerAxis*(numaxis+1) ; i++){
indexOfValue = findIndexOfClosestValue(sampling_value, numaxis);
printf("%i: %i => %i\t", i, sampling_value, indexOfValue);
MagSamples[i][0] = MagInput[indexOfValue][0];
MagSamples[i][1] = MagInput[indexOfValue][1];
MagSamples[i][2] = MagInput[indexOfValue][2];
printf("%i %i %i\n", MagSamples[i][0], MagSamples[i][1], MagSamples[i][2]);
sampling_value = sampling_value + (magmax[numaxis]-magmin[numaxis])/samplesPerAxis;
// creates and even range between mag in min in each axis
}
printf("end axis\n");
}
printf("\nend");
}

我得到的输出:...

beginAxis: 0
0: 32648 => 263 32648 32760 32916
1: 32656 => 258 32656 32724 32888
2: 32664 => 130 32664 32754 32898
...
29: 32880 => 488 32880 32774 32804
30: 32888 => 469 32888 32706 32822
31: 32896 => 990 32896 32752 32812
32: 32904 => 973 32904 32808 32844
end axis
beginAxis: 1
33: 32624 => 463 32790 32624 32906
34: 32631 => 685 32784 32632 32884
35: 32638 => 652 32756 32638 32926
36: 32645 => 465 32833 32645 32867
...
63: 32834 => 601 32690 32834 32930
64: 32841 => 597 32689 32841 32923
65: 32848 => 627 32690 32848 32914
end axis
beginAxis: 2
66: 32769 => 511 32793 32749 32769
67: 32777 => 512 32785 32755 32777
68: 32785 => 520 32769 32731 32785
69: 32793 => 504 32853 32707 32793
...
98: 33025 => 86 32805 32775 33025
end axis

Segmentation fault: 11

这是怎么回事?

编辑:samplesPerAxis 定义为

#define samplesPerAxis 33

最佳答案

作为一个猜测,我会说错误在函数之外。函数以打印结束

 printf("\nend");

注意没有尾随的'\n',所以“结束”直到稍后才会被刷新。因此您在输出中看不到它。与此同时,您继续并遇到错误。

编辑:

i think you are right. Could you elaborate on how the flush would 
process with the trailing \n?

printf 函数缓冲您发送到 stdout 的内容,并在遇到换行符 '\n'(在您给它)。要在不添加换行符的情况下强制刷新,您可以使用 fflush(stdout);

关于c - c中for循环的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13485039/

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