2014-10-17 57 views
0
#include <stdio.h> 
#include <math.h> 

#define MAXVALS 100 

typedef struct { 
    double x,y; 
} location_t; 

typedef struct { 
    location_t loc; 
    double sos; 
} loc_sos_t; 

int 
main(int argc,char *argv[]){ 

int line_count = 0, i=0; 
double temp_x, temp_y, temp_watt; 


location_t loc_str[MAXVALS]; 
loc_sos_t sos_str[MAXVALS]; 

while (scanf("%lf %lf %lf", &temp_x, &temp_y, &temp_watt) == 3){ 
    loc_str[i].x = temp_x; 
    loc_str[i].y = temp_y; 
    sos_str[i].sos = temp_watt; 

    i+=1; 
    line_count+=1;} 
for (i=0; i<5; i++){ 
    printf("x= %lf, y= %lf\n", sos_str[i].loc.x, sos_str[i].loc.y); 

} 
printf("line count = %d", line_count); 
return 0; 
} 


input file 
30.0 70.0 0.0045 
53.0 63.0 0.0006 
36.5 27.0 0.0005 
70.0 25.0 0.0015 
20.0 50.0 0.0008 
columns are X coordinates, Y coordiantes, watts 

我试图从输入文本文件中读取值并将它们放入2个不同的结构中。第一个结构需要有X和Y坐标,而第二个结构需要有(X,Y)和瓦特。最后一个循环是检查值是否存在于结构中。当我尝试从第二个结构访问X和Y坐标时,它会给我零。请告诉我出了什么问题,以及如何解决问题,如果您特别慷慨,如何改进我的代码以便看起来更优雅。如何访问嵌套结构中的项目

+0

thanks maaaaaaaan – 2014-10-18 16:55:11

回答

1
location_t loc_str[MAXVALS]; 
... 
loc_str[i].x = temp_x; 
loc_str[i].y = temp_y; 

您正在设置的位置与您的sos_str数组无关。摆脱loc_str并做

sos_str[i].loc.x = temp_x; 
sos_str[i].loc.y = temp_y; 
+0

thanks maaaaaan – 2014-10-18 16:54:28

1

你可以做任何

location_t loc_str[MAXVALS]; 
... 
sos_str[i].loc.x = temp_x; 
sos_str[i].loc.y = temp_y; 

typedef struct { 
    location_t *loc; 
    double sos; 
} loc_sos_t; 
.... 
location_t loc_str[MAXVALS]; 
loc_sos_t sos_str[MAXVALS]; 
... 
loc_str[i].x = temp_x; 
loc_str[i].y = temp_y; 
sos_str[i].sos = temp_watt; 
sos_str[i].loc = &loc_str[i]; 

第二个选项增加了不必要的复杂性,但它有助于解释什么地方出了问题你的代码。 当您创建数组sos_str时,您实际上也会创建空间来容纳MAXVALS数量的location_t。要访问该空间,您需要sos_str [i] .loc,就像访问结构中任何字段的方式一样。 在第二个选项中,您需要创建两个数组,因为loc_sos_t不再包含location_t。相反,它包含一个指向location_t的指针,其内存需要在别处分配。当包含的结构需要动态分配时,将指针指定为结构字段更为常见。

+0

thanks maaaaaaan – 2014-10-18 16:54:54