gpt4 book ai didi

c - 返回值或传递指针作为参数?

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:11 24 4
gpt4 key购买 nike

我了解到,为了通过调用函数访问或修改变量的值,我们需要将指针作为参数传递,如下所示:

#include <stdio.h>

//create a function
void Increment(int* x) {
*x = *x+1;
printf("Address of variable x in increment = %p\n",x);

}

int main() {
int a;
a = 10;
Increment(&a);
printf("Address of variable 'a' in main = %p\n",&a);
printf("Value of a in main function = %d\n",a);


}

但是我又做了一次测试,发现通过调用函数并返回值,我也可以达到同样的结果。

#include <stdio.h>

//create a function
int Increment(int x) { // do not use VOID
x = x+1;
printf("Address of variable x in increment = %p\n",x);
return x;

}

int main() {
int a;
a = 10;
int hasil;
hasil = Increment(a);
printf("Address of variable 'a' in main = %p\n",&a);
printf("Value of a in main function = %d\n",hasil);


}

我的问题:

1) 如果我只能使用返回值来获得相同的结果,是否必须将指针作为参数传递?

2) 当我从返回值的函数打印变量“x”的内存地址时,我观察到内存地址非常短 0xb ,知道为什么吗?通常地址很长。

最佳答案

1) Do I have to pass pointers as argument if I can just use return value to achieve the same result?

不,您不必总是这样做。但是观察它释放了函数的返回值用于错误报告。一个非常简单的例子:

enum error_code {
E_SUCCESS,
E_GENERAL_FAILURE,
E_MEMORY_ALLOCATION_FAILED,
E_INVALID_ARGUMENT,
E_FILE_NOT_EXIST
};

struct my_important_data {
// stuff
};

enum error_code fill_important_data_from_file(char const *file_name,
struct my_important_data **data)
{
if(!data || !file_name)
return E_INVALID_ARGUMENT;

*data = malloc(sizeof(**data));

if(!*data)
return E_MEMORY_ALLOCATION_FAILED;

// Return different error codes based on type of failure
// so the caller can know what exactly went wrong

return E_SUCCESS;
}

2) I observe when I print the address of the memory of variable 'x' from the function that returns value, the memory address is very short 0xb , any idea why? normally the address is very long.

那是因为您正在使用 %p 转换说明符来打印常规 int,而不是实际地址。严格来说,这会导致 printf 函数具有未定义的行为。

关于c - 返回值或传递指针作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42922582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com