Does using calloc inside function, change the pointer passed as function argument

前端 未结 2 1729
借酒劲吻你
借酒劲吻你 2020-12-21 21:05

I do not understand why the second printf loop outputs different data than the first printf loop that was done inside the function scope. Can it be that the pointer is ch

2条回答
  •  庸人自扰
    2020-12-21 21:38

    There are different mistakes:

    When you pass a parameter to a function it is always copied. You gave a char **parts and it is copied.

    Inside the function you overwrite the copied input with the new address of the calloced pointer.

    Consider an easier example:

    void doSomething(int a){
      a=5;
    }
    ///...
    int b = 6;
    doSomething(b);
    

    When you call doSomething(b), your b is not changed. If you want it to be changed, you have to pass a pointer to b.

    void doSomething(int* a){
      *a=5;
    }
    ///...
    int b = 6;
    doSomething(&b);
    

    The same is with your char*array.

    You have char** partsin your main, that you want to be set to the allocated array. so you have to pass its pointer. and write the obtained address to the dereferenced pointer.

    The other big mistake is, that you gibe the wrong soze to the first calloc. It should be sizeof(char*).

    Your routine should start like this:

    void ProtocolParse_Start(int *numParts,char ***parts, char *str, const char* partsDelim )
    {
      int partCount = strChrCount(str,'~');
      *numParts = partCount;
    
      *parts = (char**)calloc(partCount,sizeof(char*));
      char *tempPart;
      //...
    

    (all further accesses to parts in the function have to dereference parts)

    and the call have to look like:

    ProtocolParse_Start(&numParts, &parts,proto,"~");
    

提交回复
热议问题