数组的自由第一个元素

War*_*ers 1 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);
}
Run Code Online (Sandbox Code Playgroud)

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

ex *_*ilo 5

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

更新

@chux 在评论中提出了几点好处.

首先,而不是在出现故障退出realloc(),它可能是更好的只是继续没有重新分配tempa; 毕竟,a确实指向了预期的字符串,分配的内存只会比必要的大一点.

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

以下是上述代码的更一般版本,其中包含以下建议:

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

int main(void)
{
    char *s = "foo bar";
    char *a = malloc(sizeof *a * (strlen(s) + 1));
    strcpy(a, s);

    puts(a);

    size_t rest = strlen(a);

    /* Don't do anything if a is an empty string */
    if (rest) {
        memmove(a, a+1, rest);

        /* If you must reallocate */
        char *temp = realloc(a, rest);
        if (temp) {
            a = temp;
        }
    }

    puts(a);

    free(a);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)