在我的函数中出现错误,该函数使用 C 中的指针返回数组中的值
我正在尝试学习 C 语言中的数组和指针。我正在尝试编写一个函数中的程序:从用户处获取 2 个数字,将它们放入数组中,然后将它们返回到主函数。我收到错误,但我不明白问题是什么。这是我的代码:
#include<stdio.h>
void get_nums(float *x)
{
float num1, num2;
printf("enter two numbers: ");
scanf("%f %f", &num1, &num2);
*x[0] = num1;
*x[1] = num2;
}
main(){
float x[2];
float (*p_x)[2] = &x;
get_nums(p_x[2]);
printf("Number 1: %f\nNumber 2: %f", x[0], x[1]);
return 0;
}
我在这两行上收到错误
*x[0] = num1;
*x[1] = num2;
错误消息是
错误:“*”的操作数必须是指针
我不明白这是什么错误。有人看到问题所在吗?
编辑:我将这两行更改为
x[0] = num1;
x[1] = num2;
,现在我可以运行该程序。但是,在输入这两个数字后,我收到了新的错误。错误信息是:
arraysandpointers.exe 中 0x40e00000 处未处理的异常:0xC0000005:访问冲突。
I am trying to learn arrays and pointers in C. I'm trying to write a program that in a function: gets 2 numbers from the user, puts them in an array, and returns them to the main function. I am getting an error and I don't understand what the problem is. Here is my code:
#include<stdio.h>
void get_nums(float *x)
{
float num1, num2;
printf("enter two numbers: ");
scanf("%f %f", &num1, &num2);
*x[0] = num1;
*x[1] = num2;
}
main(){
float x[2];
float (*p_x)[2] = &x;
get_nums(p_x[2]);
printf("Number 1: %f\nNumber 2: %f", x[0], x[1]);
return 0;
}
I am getting an error on these 2 lines
*x[0] = num1;
*x[1] = num2;
The error message is
Error: operand of '*' must be a pointer
I don't see what it is that is wrong. Does anyone see the problem?
EDIT: I changed the 2 lines to
x[0] = num1;
x[1] = num2;
and now I can run the program. However I get a new error after I enter the two numbers. The error message is:
Unhandled exception at 0x40e00000 in arraysandpointers.exe: 0xC0000005: Access violation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要
*
。这很好:在您的原始代码中,
x[0]
已经是float
类型。*x[0]
将尝试遵循它 - 这是不可能的,因为x[0]
不是指针。因此它无法编译。编辑:还将您的 main 更改为:
不需要
p_x
。这就是导致坠机的原因。You don't need the
*
. Just this is fine:In your original code
x[0]
already is of typefloat
.*x[0]
will try to deference it - which is not possible sincex[0]
isn't a pointer. Therefore it doesn't compile.EDIT : Also change your main to this:
It is not necessary to have the
p_x
. And it is what's causing the crash.*X
可以被认为是X
的数组,就像X[]
一样。因此,当您编写为*X[0]
时,它会被视为二维数组。因此删除X[0]
和X[1]
中的指针。删除这两行:
您可以直接执行
get_nums(x)
。*X
can be considered as an array ofX
likeX[]
. So when you are writing as*X[0]
it considers as a 2D array. So remove the pointers inX[0]
andX[1]
.Remove these two lines:
You can directly do
get_nums(x)
.