我有一个使用线条绘制算法绘制线条的程序。我在Xubuntu 15.10上使用gcc 5.2.1
来编译它。
执行它会引发"段违规"故障。进一步的调查让我在这个MCVE中找出了问题:
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned char byte;
typedef struct {
uint x;
uint y;
} point;
typedef struct {
point start;
point end;
} line;
line new_line(point start, point end) {
line l;
l.start = start; l.end = end;
return l;
}
point new_point(uint x, uint y) {
point p;
p.x = x; p.y = y;
return p;
}
byte points_equal(point p1, point p2) {
int equal = (p1.x == p2.x && p1.y == p2.y) ? 1 : 0;
return equal;
}
double line_slope(line l) {
return (double) (l.end.y - l.start.y) / (l.end.x - l.start.x);
}
/* Naive line drawing algorithm: assumes line in 1st octant */
point * naive(line l) {
uint numelems = abs( l.end.x - l.start.x );
double m = line_slope(l);
point * tbl = calloc(numelems + 1, sizeof *tbl);
if (tbl == NULL) return NULL;
int x, nt;
double b = (double) l.start.y - ((double) l.start.x * m);
tbl[0] = l.start;
tbl[numelems] = l.end;
for (x = l.start.x + 1, nt = 1; nt < numelems; x++, nt++) {
tbl[nt].x = x;
tbl[nt].y = (int) ( m*x + b );
}
return tbl;
}
/* Main program */
int main() {
line l = new_line( new_point( -345, -236 ), new_point( -25, -3 ) );
point *tbl = naive( l );
if (tbl != NULL) {
uint n = 0;
do {
printf("(%d,%d)\n", tbl[n].x, tbl[n].y);
} while ( !points_equal( tbl[n++], l.end ) );
free(tbl);
}
return 0;
}
该程序的输出是
(-345,-236)
(-344,1167693998)
(-343,1167693999)
(-342,1167693999)
(-341,1167694000)
(-340,1167694001)
[ output continues ]
(-30,1167694226)
(-29,1167694227)
(-28,1167694228)
(-27,1167694229)
(-26,1167694229)
(-25,-3)
我的问题出在这里:这是什么意思?结构是否会干扰演员阵容?这样的事情真的会发生吗?
提前致谢,并对此前不清楚的陈述感到抱歉。愿这个重新制作的问题(以及随后的答案)成为自我学习的证明,并且愿意将Stack Overflow保持在最佳状态。
答案 0 :(得分:0)
point.x
和point.y
中使用的类型:
typedef unsigned int uint;
typedef struct {
uint x;
uint y;
} point;
由于两者都是无符号整数,所以&#34;总结&#34;一旦他们收到负值,就像在MCVE中一样。只需将uint
更改为int
即可解决此问题。
所以在使用有符号和无符号数字时请记住这一点!