[英]Trying to pass a value to a function that takes a pointer as argument
我一直在寻找答案,但一直没有找到可行的解决方案。 正如您在下面的代码中看到的那样,我试图将选择的值传递给 get_user_input(char *input)。 我认为这就是我想要做的,因为我需要在 get_user_input(char *input) 中调用函数 scanf。
我对编程还很陌生,在尝试理解指针和引用时遇到了很多麻烦
我希望有人可以帮助我!
get_user_input(char input) 函数
void get_user_input(char *input) {
*input = '\0' ;
scanf(" %c", input);
}
试图从函数 get_user_input(char input)调用 scanf( )
void manual_read_sensors(void) {
while (1) {
// Ask the user for which sensor to read.
printf("Which sensor do you want to read?\n"
"(i)ntensity\n"
"(a)ngle\n"
"(t)ime\n"
"(s)unscreen\n"
"(q)uit\n"
"Enter choice: ");
void choice = get_user_input(); <----- Trying to call
// Return to the main menu again.
if (choice == 'q')
break;
首先,您的get_user_input
函数接受一个char *
并且不返回任何内容,但您没有传递任何内容 - 您应该传递choice
的地址,例如: get_user_input(&choice);
. 如果您传递choice
的地址, get_user_input
函数将能够向其写入数据。
其次, void choice
不是有效的声明。 尽管您可以声明void *choice
。 在这种情况下,您应该将choice
声明为char
: char choice;
.
第三, get_user_input
不返回任何内容,您不应该尝试将函数的结果分配给变量。
四、 *input = '\\0' ;
在下一步中没有实现任何目标,您使用scanf
覆盖input
。
get_user_input
应如下所示:
void get_user_input(char *input) {
scanf(" %c", input);
}
manual_read_sensors
应如下所示:
void manual_read_sensors(void) {
char choice;
while (1) {
// Ask the user for which sensor to read.
printf("Which sensor do you want to read?\n"
"(i)ntensity\n"
"(a)ngle\n"
"(t)ime\n"
"(s)unscreen\n"
"(q)uit\n"
"Enter choice: ");
get_user_input(&choice);
// Return to the main menu again.
if (choice == 'q')
break;
您已声明get_user_input()函数将 char 引用作为其参数。 但是当从manual_read_sensors()函数调用这个函数时,没有传递给 get_user_input() 函数的引用。
选择变量不能声明为 void 类型,因为这在 C/C++ 语言( 参考)中是不允许的。 而是尝试声明,
char choice;
由于get_user_input()函数被声明为以void作为返回类型,它不能向其他函数返回任何值,因此,不能像这样为变量赋值,
char choice = get_user_input(); //error
由于get_user_input()不返回任何值,我们需要使用指针变量来操作选择变量。 但是指针变量也需要指向变量的地址,这就是为什么我们需要将选择变量的引用(或地址)传递给get_user_input()函数的原因。 像这样,
get_user_input(&choice);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.