以下是代码片段
Obj *temp;
temp = new Sphere(center, radius);
struct color c = {1, 0, 0};
temp->setColor(c); //works fine
temp->setShine(1); //works fine
temp->setCoefficients(0.4, 0.2, 0.2, 0.2); //works fine
temp->draw(); //NULL pointer!!
objects.push_back(temp);
temp = new Floor(1000, 20);
temp->draw(); //works fine too!
objects.push_back(temp);其中Obj是基类,Sphere和Floor是派生类,draw是虚拟方法。
在此之前,我的绘图函数工作得很好,并且没有指针问题。突然,我收到了这个exc-bad-access错误,我调试后发现,无论我在哪里调用Sphere::draw()," this“指针都会变为空。
(我在这里无法正确粘贴Sphere::draw()函数。)
glPushMatrix();
{
glColor3f(c.r, c.g, c.b);
glTranslatef(referencePoint.x, referencePoint.y, referencePoint.z);
printf("inside sphere draw\n");
double radius = length;
struct point points[1000][1000];
int stacks = 1000, slices = 1000;
int i,j;
double h,r;
//generate points
for(i=0;i<=stacks;i++)
{
h=radius*sin(((double)i/(double)stacks)*(pi/2));
r=radius*cos(((double)i/(double)stacks)*(pi/2));
for(j=0;j<=slices;j++)
{
points[i][j].x=r*cos(((double)j/(double)slices)*2*pi);
points[i][j].y=r*sin(((double)j/(double)slices)*2*pi);
points[i][j].z=h;
}
}
//draw quads using generated points
for(i=0;i<stacks;i++)
{
glColor3f(1.0, 0, 0);
//glColor3f((double)i/(double)stacks,(double)i/(double)stacks,(double)i/(double)stacks);
for(j=0;j<slices;j++)
{
glBegin(GL_QUADS);
{
//upper hemisphere
glVertex3f(points[i][j].x,points[i][j].y,points[i][j].z);
glVertex3f(points[i][j+1].x,points[i][j+1].y,points[i][j+1].z);
glVertex3f(points[i+1][j+1].x,points[i+1][j+1].y,points[i+1][j+1].z);
glVertex3f(points[i+1][j].x,points[i+1][j].y,points[i+1][j].z);
//lower hemisphere
glVertex3f(points[i][j].x,points[i][j].y,-points[i][j].z);
glVertex3f(points[i][j+1].x,points[i][j+1].y,-points[i][j+1].z);
glVertex3f(points[i+1][j+1].x,points[i+1][j+1].y,-points[i+1][j+1].z);
glVertex3f(points[i+1][j].x,points[i+1][j].y,-points[i+1][j].z);
}glEnd();
}
}
}glPopMatrix();}
发布于 2017-05-24 18:05:40
指针不是空的,你只是试着写一些超出数组边界的东西。这里:
for(i=0;i<=stacks;i++)这里:
for(j=0;j<=slices;j++)这个数组的最后一个元素是pointsstacks-1,在您的循环条件中,您试图在最后一次迭代中引用pointsstacks。
此外,在这些代码行中还有另一个问题:
这里:
glVertex3f(points[i][j+1].x,points[i][j+1].y,points[i][j+1].z);
glVertex3f(points[i+1][j+1].x,points[i+1][j+1].y,points[i+1][j+1].z);
glVertex3f(points[i+1][j].x,points[i+1][j].y,points[i+1][j].z);还有这里:
glVertex3f(points[i][j+1].x,points[i][j+1].y,-points[i][j+1].z);
glVertex3f(points[i+1][j+1].x,points[i+1][j+1].y,-points[i+1][j+1].z);
glVertex3f(points[i+1][j].x,points[i+1][j].y,-points[i+1][j].z);这些[i+1]、[j+1]部件正试图在上一次迭代中执行与上述相同的操作。
https://stackoverflow.com/questions/44154197
复制相似问题