数组的自由第一个元素

时间:2017-08-18 13:51:34

标签: c arrays malloc free

当我使用malloc分配数组时,有没有办法只释放数组的第一个元素?

一个小例子:

#include <stdlib.h>
#include <string.h>

int main() {
    char * a = malloc(sizeof(char) * 8);
    strcpy(a, "foo bar");

    // How I would have to do this.
    char * b = malloc(sizeof(char) * 7);
    strcpy(b, a+1);


    free(a);
    free(b);
}

有没有办法只释放a的第一个字符,以便我可以使用a+1使用字符串的其余部分?

2 个答案:

答案 0 :(得分:5)

如果要删除a的第一个字符,可以使用memmove()将字符串中的其余字符向左移动1,然后使用{{1}如果需要缩小分配:

realloc()

更新

@chux在good points中制作了几个the comments

首先,不要退出#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char * a = malloc(sizeof(char) * 8); strcpy(a, "foo bar"); puts(a); size_t rest = strlen(a); memmove(a, a+1, rest); /* If you must reallocate */ char *temp = realloc(a, rest); if (temp == NULL) { perror("Unable to reallocate"); exit(EXIT_FAILURE); } a = temp; puts(a); free(a); return 0; } 中的失败,最好只是继续而不将realloc()重新分配给temp;毕竟,a确实指向了预期的字符串,分配的内存只会比必要的大一点。

其次,如果输入字符串为空,则a将为0.这会导致rest出现问题。一种解决方案是在修改realloc(a, rest)指向的字符串之前检查rest == 0

以上代码的稍微更一般的版本包含以下建议:

a

答案 1 :(得分:0)

  

有没有办法释放

的第一个字符

没有。你不能释放a的第一个字符,因为它是char类型。只有malloc族函数返回的指针才能被释放。 你可以做到这一点。

char * a = malloc(sizeof(char) * 8);
strcpy(a, "foo bar");
char * b = malloc(strlen(a));
strcpy(b, a+1);
free(a);
相关问题