gpt4 book ai didi

c - 带有指向 C 中数组参数的指针的函数

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

我在下面编写了代码,其中包含一个函数,该函数带有一个指向大小为 3 的 double 组的指针。我的问题是:当我将指针的地址传递给一个 double 变量 (显然不是数组) 然后想要更改函数“f”中这个 double 变量的值时,如下所示,当我实现这样,结果是正确的,变量的值被改变了:

#include <stdio.h>
void f(double (*)[3]);
double a = 7.5;

int main()
{
double* b = &a;
f(&b);
printf("a = %lf\n", a);
return 0;

}
void f(double (*hi)[3])
{
double **sth = (double **) hi;\
*(*sth) = 1;

}

但是当我如下实现时,值没有改变:

void f(double (*hi)[3]){
(*hi)[0] = 1;
}

我们将不胜感激任何想法和建议。

最佳答案

首先修复程序给出的编译错误。解决这些问题后,您就会知道问题所在。

prog.c: In function 'main':
prog.c:8:6: error: passing argument 1 of 'f' from incompatible pointer type [-Werror=incompatible-pointer-types]
f(&b);
^
prog.c:2:6: note: expected 'double (*)[3]' but argument is of type 'double **'
void f(double (*)[3]);

http://ideone.com/mueyCU

#include <stdio.h>
void f(double (*)[3]);
double a = 7.5;

int main()
{
double* b = &a;
f(b);
printf("a = %lf\n", a);
return 0;

}

void f(double (*hi)[3]){
(*hi)[0] = 1;
}

以上代码不是正确的做事方式,应不惜一切代价避免。

关于c - 带有指向 C 中数组参数的指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33058419/

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