0

我正在编写一个程序,我试图在主结构中为一个结构数组分配内存,然后将该数组传递给一个函数,该函数从文件中读取数据,创建结构并用创建的结构填充数组。

由于某种原因,这段代码只为数组中的 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);

}

这是我从运行主程序中得到的输出;

37 8 8 600 180 180 818 180 600

程序首先打印出 assets_size,即 37。然后它打印出 assets 数组的大小,它应该是 37,但是是 8。再次相同。然后它会打印出所有已填充到阵列中的资产的部署时间,即只有 7 个。

请问有人能告诉我哪里出错了吗?

4

1 回答 1

3

问题在于您在 main 中的 for 循环中打印部署时间,sizeof(assets)没有给您数组的长度,没有办法获得仅由简单指针指向的数组的长度。sizeof(assets)为您提供 chars 中指针的大小,因为您显然是在 64 位平台上工作,所以它是 8。只需从 0 运行到asset_size.

为什么要read_data为每个资产分配一个新结构,只需直接写入资产数组即可。

在主要做:

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;
    ...
}
于 2013-11-14T15:52:54.463 回答