【发布时间】:2013-12-10 13:30:15
【问题描述】:
我提出了一个新问题,因为我认为这与我之前的问题不同:Trouble looping through arrays define in other source files
我目前遇到的问题是我通过引用另一个函数传入 size_t 值,然后我在该函数中设置所述 size_t 的值,然后我可以在另一个函数中设置。
我面临的问题是,当我传入 size_t 变量时,设置值的函数会正确设置它的值,但是当我返回声明变量的源文件时,它再次具有“随机”值。
有人知道为什么会这样吗?
system_handler.c
size_t ship_size;
size_t asset_size;
mayday_call* mday_ptr;
ship* ship_ptr;
rescue_asset* assets_ptr;
mday_ptr = read_mayday_file();
ship_ptr = read_ship_locations(&ship_size);
assets_ptr = read_recuse_assets(&asset_size);
printf("ships size : %d\n", ship_size);
printf("assets size : %d\n", asset_size);
ship.c
ship* read_ship_locations(size_t* size){
//no_of_lines is an unsigned int
//locof is a char array containing a file name
no_of_lines = (count_lines(locof) -1 );
printf("number of lines = %d \n", no_of_lines);
size = (unsigned int)no_of_lines;
size = no_of_lines;
}
rescue_assets.c
rescue_asset* read_rescue_assets(size_t* size) {
//no_of_lines is an unsigned int
//locof is a char array containing a file name
no_of_lines = count_lines(locof);
printf("number of lines = %d \n", no_of_lines);
assets = calloc(no_of_lines,sizeof (rescue_asset));
size = (unsigned int)no_of_lines;
printf("size : %d\n", size);
}
控制台输出:
please enter the file name for the ship locations data:
ships_1.txt
number of lines = 4
size : 4
Please enter the file name for the rescue assets data:
rescue_assets.txt
number of lines = 37
size : 37
ships size : 134513984
assets size : 0
【问题讨论】:
-
糟糕! C 中不能通过引用传递!!
标签: c parameter-passing pass-by-reference