通过引用而不保持其整数值

时间:2013-11-25 17:36:34

标签: c parameter-passing pass-by-reference

我正在提出一个新问题,因为我认为这与我之前关于我之前问题的问题不同: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

2 个答案:

答案 0 :(得分:9)

正如评论者所说,C不支持真正的传递参考;你要做的就是传递变量的地址,并将其用作函数体中的指针。如果size被声明为指向size_t的指针,则需要明确地引用它:

*size = (size_t)no_of_lines;

而不是

size = (size_t)no_of_lines;

编辑:使用gcc -Wall进行编译会发出一个类型转换警告,可以解释这个问题。

答案 1 :(得分:3)

正如haccks评论的那样:C中没有传递引用。当你传递size_t的地址时,它们只是:地址。当您在no_of_lines中将size分配给read_ship_locations时,您正在更改该地址本地。你需要取消引用地址并分配给它:

*size = no_of_lines;

提示:我假设您将no_of_lines强制转换为(unsigned int),因为编译器会在您不这样做时警告有关int-to-pointer的转换。当编译器建议您不打算使用某个版本时,它几乎总是解决您的问题。在这种情况下:当您将no_of_lines分配给size时,您要将int分配给size_t *,这不是一个好主意,因为地址no_of_lines很可能不是有效的。

相关问题