简体   繁体   English

如何持久化指针增量

[英]how to persist the pointer increment

I have the following code我有以下代码

   void fun(int * d)
   {
    d+=1;
   }

   int main()
   {
      int * f=malloc(5);
      f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
      fun(f);
      printf("value : %d\n",*f);
      return 0;
   }

So, i pass an integer pointer to function and increment it there.所以,我将一个整数指针传递给函数并在那里增加它。 I want that increment to persist when it returns to main.我希望该增量在返回 main 时保持不变。 When I print the value, The output is '0'.当我打印值时,输出为“0”。 But I want the output to be '1' as I have incremented the value in function.但我希望输出为“1”,因为我增加了函数中的值。

So, briefly, my question is, how to persist the changes made to a pointer?所以,简而言之,我的问题是,如何保持对指针所做的更改?

Assuming you want to increment the pointer , not the value, you have two options:假设您想增加指针而不是值,您有两个选择:

  1. recast the function to void fun(int ** d) , use (*d)+=1;将函数重铸为void fun(int ** d) ,使用(*d)+=1; in the function body, and call using fun(&f);在函数体中,并使用fun(&f);

  2. recast the function to int* fun(int* d) , and return the new value.将函数重铸为int* fun(int* d) ,并返回新值。

If you want to increase the value , then use (*d)+=1;如果要增加,则使用(*d)+=1; in the function body.在函数体中。

You don't need the parentheses around *d : I've put them in for clarity.你不需要*d周围的括号:为了清楚起见,我把它们放在了里面。

You forgot * in d+=1;你在 d+=1 中忘记了 *;

When you pass that pointer you have access to f[0] with that approach: Take a look here:当您传递该指针时,您可以使用该方法访问 f[0]:看看这里:

#include <stdio.h>
#include<stdlib.h>

void fun(int *d){
    *d+=1;
}

int main(void){
    int i;
    int *f=malloc(5 * sizeof int);

    f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;

    for(i=0;i<5;i++){
        printf("%d ",f[i]);
    }

    printf("\n");

    fun(f);

    for(i=0;i<5;i++){
        printf("%d ",f[i]);
    }
    free(f);
    return 0;
}

Output:输出:

 0 1 2 3 4 1 1 2 3 4

Or if you try to add +1 to all elements you can do something like this:或者,如果您尝试为所有元素添加 +1,您可以执行以下操作:

#include <stdio.h>
#include<stdlib.h>

int *fun(int *d, int len){
    int i;
    int *newArray = d;
    int newValue = 1;

    printf("\n");
    for(i = 0; i < len; i++) {
        newArray[i] += newValue;
    }

    return newArray;
}

int main(void){
    int i;
    int f[] = {0,1,2,3,4};
    int *newArray;

    f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;

    for(i=0;i<5;i++){
        printf("%d ",f[i]);
    }

    printf("\n");



    newArray = fun(f,5);

    for(i=0;i<5;i++){
        printf("%d ",newArray[i]);
    }
    return 0;
}

Output:输出:

 0 1 2 3 4 1 2 3 4 5

And by the way you forgot to free f .顺便说一下,您忘记释放f

You have to pass the address of the pointer, so:您必须传递指针的地址,因此:

void fun(int **val) {
    *val++;
    ....
}
int main() {
    ...
    fun(&f);
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM