开发者

How to increase the size of a block which an argument of a function points to?

开发者 https://www.devze.com 2023-02-13 08:31 出处:网络
void foo(char *p) { int i; int len = strlen(p); p = malloc(sizeof(char)*len+2); p[0] = \'1\'; for(i=1; i<len+1; i++)
void foo(char *p)  
{  
    int i;
    int len = strlen(p);
    p = malloc(sizeof(char)*len+2);
    p[0] = '1';
    for(i=1; i<len+1; i++)
        p[i] = '0';
    p[i] = '\0';
}  

int main()  
{
    char p[2] = "1";

    foo(p);
    printf("%s\n", p);  // "10" expected

 开发者_JAVA百科   return 0;
}

I realized that when I call malloc in foo, p's value has been changed, so array p in main will not be influence. But I don't know how to correct it.


You have a few wrong things with your code:

  • In main, you declare p as an array that resides on the stack. Things that are on the stack cannot later be resized.

  • Then in foo you want to change p to point to memory from the heap rather than to the array you have declared.

What you want to achieve can be done by initially allocating p with malloc, and then reallocating that memory again with realloc:

void foo (char **p) {
  *p = realloc(*p, 4);
}

int main (void) {
  char *p = malloc(2);
  foo(&p);
  ...
}

Notice that the argument of foo is a double pointer. That's because realloc may not only resize the memory block, but it may actually move it as well, so it will affect the value of the pointer.

Also note that the second argument of realloc is not the size you want to increment with, but rather the current size of the block plus the size to increment with.


You need to pass the address of the pointer and take char** as the function argument, i.e. pass &p as the argument and use *p inside foo to get the array address. BTW, the initialization of array needs to be done char p[2] = {'1'};

0

精彩评论

暂无评论...
验证码 换一张
取 消