英文:
How to change the value of a variable passed as an argument and also use the value for an array
问题
这是我的示例代码:
#include <stdio.h>
void Func(int a[], int b) {
a[b] = 1;
b += 5;
}
int main(void) {
int a[10];
int b = 0;
printf("%d\n", b);
Func(a, b);
printf("%d\n", a[0]);
printf("%d\n", b);
}
我想让程序打印出:
0
1
5
我尝试通过将b
改为指针来更改函数:
void Func(int a[], int *b)
... 并写上*b += 5
。另外,我改变了函数的调用方式:
int a[10];
int *b = 0;
// ...
Func(a, &b);
能够操纵b
并使用它吗?
注:我尝试遵循这个帖子。
英文:
This is my example code:
#include <stdio.h>
void Func(int a[], int b) {
a[b] = 1;
b += 5;
}
int main(void) {
int a[10];
int b = 0;
printf("%d\n", b);
Func(a, b);
printf("%d\n", a[0]);
printf("%d\n", b);
}
And I want the program to print:
0
1
5
I've tried changing the function by making b
a pointer:
void Func(int a[], int *b)
... and by writing *b += 5
. Also, I've changed the call of the function to:
int a[10];
int *b = 0;
// ...
Func(a, &b);
Is it possible to manipulate b
and to use it?
Note: I've tried following this post
答案1
得分: 3
void Func(int a[], int *b) {
a[*b] = 1;
*b += 5;
}
int main(void) {
int a[10];
int b = 0;
printf("%d\n", b); // 打印变量 b 的值
Func(a, &b); // 将变量 b 的地址传递给 Func
printf("%d\n", a[0]);
printf("%d\n", b); // 再次打印变量 b 的值
}
Func
仍然有一个名为 b
的本地副本,但这个副本是一个指针,可以指向 main
中的 b
对象。这允许我们使用 *b += 5
修改指向的对象。
英文:
> c
> void Func(int a[], int b){
> a[b] = 1; // OK
> b += 5; // useless
> }
>
The problem with this code is that Func
is assigning a local copy of b
, and this has no effect outside of the function.
To get the expected output:
#include <stdio.h>
void Func(int a[], int *b) {
a[*b] = 1;
*b += 5;
}
int main(void) {
int a[10];
int b = 0;
printf("%d\n", b); // print value of b
Func(a, &b); // pass address of b to Func
printf("%d\n", a[0]);
printf("%d\n", b); // print value of b again
}
Func
still has a local copy named b
, but this copy is a pointer which may point to the b
object in main
. This allows us to modify the pointed-to object with *b += 5
.
答案2
得分: 1
你需要将a
和b
用作指针,因为a
是一个数组,而你想要在函数内修改b
的值。
但是你不能直接将b
直接传递给函数,这就是为什么要将其作为&b
发送,以提供变量存储的地址,这样你就不会复制b
的值,而是直接改变它。
void foo(int *a, int *b) {
a[*b] = 1;
*b += 5;
}
int main(void) {
int a[10] = {0};
int b = 0;
printf("b = [%i]\n", b);
foo(a, &b);
printf("a[0] = [%i]\n", a[b]);
printf("b = [%i]\n", b);
}
英文:
For that you want to use a
and b
as a pointer, because a
is an array and b
you want to modify the value inside the function.
But you can't send directly b
inside the function is why you to send as &b
to give the address where the variable is stored in that way you don't copy the value of b
but directly change it.
void foo(int *a, int *b) {
a[*b] = 1;
*b += 5;
}
int main(void) {
int a[10] = {0};
int b = 0;
printf("b = [%i]\n", b);
foo(a, &b);
printf("a[0] = [%i]\n", a[b]);
printf("b = [%i]\n", b);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论