我正在编写一个程序,我试图在main中为一个结构数组分配内存然后将数组传递给一个从文件中读取数据的函数,创建结构并使用创建的结构填充数组
由于某种原因,这段代码只为数组中的7个元素分配足够的内存;
int assets_size = count_lines("rescue_assets.txt");
asset *assets;
assets = (asset*)malloc(sizeof(asset)*assets_size);
文件中的行数为37,并且count_lines方法可以正常工作,因为它在主文件中进行了测试。
以下是main的完整代码;
int main(int argc, char** argv) {
int i;
int assets_size = count_lines("rescue_assets.txt");
asset *assets;
assets = (asset*)malloc(sizeof(asset)*assets_size);
ship ships[100];
printf("%d\n", assets_size);
printf("%lu\n", sizeof(assets));
read_data(assets, ships);
printf("%lu\n", sizeof(assets));
for (i=0; i<sizeof(assets)-1; i++) {
printf("%d\n", assets[i].deployment_time);
}
free(assets);
return (EXIT_SUCCESS);
}
以下是函数read_data;
的相关代码void read_data(asset *assets, ship ships[]) {
int max_assets;
int max_ships;
FILE *asset_file_ptr;
FILE *ship_file_ptr;
int count = 0;
int file_max = 100;
char asset_file[file_max];
char ship_file[file_max];
asset_file_ptr = fopen("rescue_assets.txt", "r");
if (asset_file_ptr == NULL) {
printf("The asset file could not be opened.");
exit(0);
}
else {
char callsign[file_max];
char type;
char placename[file_max];
double base_longitude;
double base_latitude;
double speed;
int deployment_time;
int service_time;
while (fscanf(asset_file_ptr, "%s %c %s %lf %lf %lf %d %d", callsign, &type, placename, &base_longitude, &base_latitude, &speed, &deployment_time, &service_time)!= EOF) {
asset* new_asset = malloc(sizeof(asset));
new_asset->callsign = callsign;
new_asset->type = type;
new_asset->placename = placename;
new_asset->base_longitude = base_longitude;
new_asset->base_latitude = base_latitude;
new_asset->speed = speed;
new_asset->deployment_time = deployment_time;
new_asset->service_time = service_time;
assets[count] = *new_asset;
count++;
}
}
fclose(asset_file_ptr);
}
这是我从运行main获得的输出;
37 8 8 600 180 180 818 180 600
程序首先打印出assets_size,即37。 然后它打印出资产数组的大小,应该是37,但是是8。 又是老样子。 然后,它会打印出已填充到阵列中的所有资产的部署时间,该资产只有7个。
请有人告诉我哪里出错了?
答案 0 :(得分:3)
问题在于你的for循环在main中打印部署时间,sizeof(assets)
没有给你数组的长度,没有办法得到一个只由一个简单指向的数组的长度指针。 sizeof(assets)
给出了字符中指针的大小,当你显然在64位平台上工作时,它是8。只需从0到asset_size
。
为什么要在每个资产的read_data
中为新结构进行mallocing,只需直接写入资产数组。
主要做:
for (int i = 0; i < size_assets; ++i)
printf("%d\n", assets[i].deployment_time);
在read_data中执行:
asset* asset_p = assets;
while (fscanf(...) != EOF) {
asset_p->field = data;
...
++asset_p;
}
或者:
int i = 0;
while (fscanf(...) != EOF) {
assets[i].field = data;
...
++i;
}
或者替代:
for (int i = 0; fscanf(...) != EOF; ++i) {
assets[i].field = data;
...
}