[英]Basic C pointer question
It has been a while since I last programmed C, seems I have forgotten everything in the meantime... I have a very simple pointer question. 自从我上次编程C以来已经有一段时间了,似乎我在此期间已经忘记了所有内容......我有一个非常简单的指针问题。 Assuming that I have a function that computes a sum through loop iteration.
假设我有一个通过循环迭代计算求和的函数。 Not only should this function return the loop counter but also the sum it computed.
此函数不仅应该返回循环计数器,还要返回它计算的总和。 Since I can just return one value I assume the best I could do for the sum is declaring a pointer.
因为我可以只返回一个值,所以我假设我能做的最好就是声明一个指针。 Can I do that like this:
我能这样做吗:
int loop_function(int* sum)
{
int len = 10;
for(j = 0; j < len; j++)
{
sum += j;
}
return(j);
}
....
int sum = 0;
loop_function(&sum);
printf("Sum is: %d", sum);
Or do I need to define an extra variable that points to sum which I pass then to the function? 或者我是否需要定义一个额外的变量,指向我传递给函数的总和?
Many thanks, Marcus 非常感谢,马库斯
What you have is correct except for this line: 你有什么是正确的,除了这一行:
sum += j;
Since sum
is a pointer, this increments the address contained in the pointer by j
, which isn't what you want. 由于
sum
是一个指针,这会使指针中包含的地址增加j
,这不是你想要的。 You want to increment the value pointed to by the pointer by j
, which is done by applying the dereference operator *
to the pointer first, like this: 您希望将指针指向的值递增
j
,这是通过首先将取消引用运算符*
应用于指针来完成的,如下所示:
*sum += j;
Also, you need to define j
somewhere in there, but I imagine you know that and it's just an oversight. 此外,你需要在那里定义
j
,但我想你知道这一点,这只是一个疏忽。
Write 写
*sum += j;
What you are doing is incrementing the pointer (Probably not what you wanted) 你正在做的是递增指针(可能不是你想要的)
It should be: 它应该是:
*sum += j;
so you increment the value pointed to instead of the local pointer variable. 所以你增加指向的值而不是本地指针变量。
You don't need to create extra variable but in the loop you need to do 您不需要创建额外的变量,但需要在循环中创建
*sum += j
You have to write *sum + = j; 你必须写* sum + = j;
This suffices 这就足够了
You could also declare a simple struct to hold the two values, then pass in a pointer to an instance of that structure. 您还可以声明一个简单的结构来保存这两个值,然后传入一个指向该结构实例的指针。 That way you could manipulate both variables and they'd retain their values after the function returns.
这样你可以操纵两个变量,并在函数返回后保留它们的值。
struct loop_sum_struct { int loop_ctr; int sum; } loop_sum; loop_function(&loop_sum); void loop_function(loop_sum_struct *s) { int len = 10; for(s->loop_ctr = 0; s->loop_ctr loop_ctr++) { s->sum += s->loop_ctr; } }
How about this ? 这个怎么样 ?
As you are already returning int. 因为你已经回归int了。 So, another way is to just change the signature to
所以,另一种方法是将签名更改为
int loop_function(int sum)
int loop_function(int sum)
and at the time of calling 在打电话的时候
int sum = 0;
int sum = 0;
...
...
sum = loop_function(sum);
sum = loop_function(sum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.