How to return a pointer as a function parameter

后端 未结 2 1818
忘了有多久
忘了有多久 2021-02-19 04:59

I\'m trying to return the data pointer from the function parameter:

bool dosomething(char *data){
    int datasize = 100;
    data = (char *)malloc(datasize);
           


        
相关标签:
2条回答
  • 2021-02-19 05:21

    You're passing by value. dosomething modifies its local copy of data - the caller will never see that.

    Use this:

    bool dosomething(char **data){
        int datasize = 100;
        *data = (char *)malloc(datasize);
        return 1;
    }
    
    char *data = NULL;
    if(dosomething(&data)){
    }
    
    0 讨论(0)
  • 2021-02-19 05:30
    int changeme(int foobar) {
      foobar = 42;
      return 0;
    }
    
    int  main(void) {
      int quux = 0;
      changeme(quux);
      /* what do you expect `quux` to have now? */
    }
    

    It's the same thing with your snippet.

    C passes everything by value.

    0 讨论(0)
提交回复
热议问题