chr*_*rds 1 c parameter-passing pass-by-reference
我正在提出一个新问题,因为我认为这与我之前关于我之前问题的问题不同:在其他源文件中循环遍历数组的麻烦
我当前的问题是我通过引用另一个函数传入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);
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
控制台输出:
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
Run Code Online (Sandbox Code Playgroud)
正如评论者所说,C不支持真正的传递参考; 你要做的就是传递变量的地址,并将其用作函数体中的指针.如果size声明为指向size_t,则需要以明确的方式引用它:
*size = (size_t)no_of_lines;
Run Code Online (Sandbox Code Playgroud)
代替
size = (size_t)no_of_lines;
Run Code Online (Sandbox Code Playgroud)
编辑:编译gcc -Wall将发出一个类型转换警告,可以解释这个问题.