2011-11-05 32 views
0

我想访问我的结构点。结构内存是动态定位的。我遇到了我无法弄清楚的分段错误。从我的.h文件中我的结构定义如下:访问从另一个图中的数字的指针C

struct point{ 
double x; 
double y; 
}; 

struct figure{ 
char name[128]; 
int draw; 
struct point *points; 
}; 

extern struct figure *figures; 

在我的.c文件我有:

struct figure *figures; 

//initializing 10 figures 
figures = malloc(10 * sizeof(struct figure)); 
//left the obvious NULL checking out for brevity 

//I'm fairly sure this portion works for initializing 10 points for each figure 
int i; 
for(i = 0;i<10;i++){ 
figures[i].points = malloc(10 * sizeof(struct point)); 
//left out NULL checking again 
} 

除非这一点,这是我在哪里遇到问题之前检测到问题,实际上将值存储到点中。 注:指标可以是任何INT> = 0,只使用一个通用术语,为简单起见

figures[index].points[index]->x = 10; 
figures[index].points[index]->y = 15; 

与他的问题任何帮助将是非常美妙的。提前致谢。

+0

用于这两个数字和点的相同索引? –

+0

不,没有数量未知的数字,点数未知。我们从文件中获取数据,我忽略了大部分代码。刚刚用于更一般情况的索引 – Kris

+0

figures [index] .points [index]是一个点,而不是一个指针指针。 –

回答

1

figures[index].points是一个结构数组,这意味着索引它(即figures[index].points[index])为您提供了一个结构。最后两行应该是:

figures[index].points[index].x = 10; 
figures[index].points[index].y = 15; 

我很惊讶编译器无法捕捉到这一点。

+0

是啊,这很奇怪......也许他没有使用gcc –

+0

格雷姆这就是我最初的想法。当我使用ddd调试器时,分段错误发生在第一行(.x) – Kris

+0

我正在使用gcc std = c99 – Kris

0

除了您错误地访问内部结构这一事实之外,在此代码中看不到任何问题。

Online Demo您的代码示例工作。

#include<string.h> 
#include<stdio.h> 

struct point{ 
double x; 
double y; 
}; 

struct figure{ 
char name[128]; 
int draw; 
struct point *points; 
}; 


int main() 
{ 
    struct figure *figures; 
    figures = malloc(10 * sizeof(struct figure)); 

    int i = 0; 
    for(i = 0;i<10;i++) 
    { 
     figures[i].points = malloc(10 * sizeof(struct point)); 
     figures[i].draw = i; 
    } 

    i = 0; 
    for(i = 0;i<10;i++) 
    { 
     printf("\nfigures[%d].draw = [%d]",i,figures[i].draw); 
     int j; 
     for(j = 0;j<10;j++) 
     { 
      figures[i].points[j].x = i; 
      figures[i].points[j].y = j; 

      printf("\nfigures[%d].points[%d].x = [%f]",i,j,figures[i].points[j].x); 
      printf("\nfigures[%d].points[%d].y = [%f]",i,j,figures[i].points[j].y); 
     } 
    } 
    return 0; 
} 

输出:

数字[0] = .draw [0]
数字[0] .points [0] .X = [0.000000]
数字[0] .points [0] .Y = [0.000000]
数字[0] .points [1] .X = [0.000000]
数字[0] .points [1] .Y = [1.000000]
数字[0 ] .points [2] .x = [0.000000]
...等等