2011-11-05 35 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]
...等等