c - 替代 malloc

标签 c

给定以下函数to_lower:

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

void to_lower(char ** strings) {
    char * original_string, lower_string;
    for (int i=0; (original_string=strings[i]) != NULL; i++) {
        lower_string = malloc(strlen(original_string)+1);
        for (int j=0; j<=strlen(original_string); j++) 
            lower_string[j] = tolower(original_string[j]);
        strings[i]=lower_string;
    }
}


int main(void) {
    char * strings[] = {"Hello", "Zerotom", "new", NULL };
    to_lower(strings);
}

是否可以在不调用malloc的情况下执行相同的功能?如果是的话,那该怎么办呢?我想看看是否可以更改指针的“值”,而不必为其分配新的内存。

最佳答案

正如评论中所指出的,您的两个问题是您打算更改常量字符串文字,并且您的函数的行为依赖于数据结构的属性(即正确终止的字符串和作为最后一个元素的 NULL 指针) 。

所以我建议在启动时设置一个固定大小的数据结构,然后设置和更改内容,最后再次清理所有内容 - 像这样:

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

#define LEN 10
#define NUM 3

char **init (int num, int len) {
    char **strings = calloc(num, sizeof(char*));
    for (int i=0; i < num; i++) {
        strings[i] = calloc(len, sizeof(char));
    }
    return strings;
}

void teardown (char **strings, int num) {
    for (int i=0; i < num; i++) {
        free(strings[i]);
    }
    free(strings);
}

void to_lower(char **strings, int num, int len) {
    for (int i=0; i < num; i++) {
        for (int j=0; j < len; j++) 
            strings[i][j] = tolower(strings[i][j]);
    }
}

int main(void) {
    // startup
    char **strings = init(NUM, LEN);

    // do things
    sprintf(strings[0], "%s", "Hello");
    sprintf(strings[1], "%s", "Zerotom");
    sprintf(strings[2], "%s", "new");
    to_lower(strings, NUM, LEN);

    // shutdown
    teardown(strings, NUM);
    return 0;
}

关于c - 替代 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128020/

相关文章:

c - 编译器和链接器之间有什么区别?

c - 二维数组地址和指向其第一个元素的相应指针

c - 将非常量参数传递给需要 const 参数的函数时发出警告。有没有更好的办法?

c - 在 4x4 网格上生成图案

c - 是否可以测试是否在 gnu Makefile 中声明了 C 定义?

c - 文件处理函数调用错误

c++ - 使用 C/C++ 访问 OS X 钥匙串(keychain)

c - if-else vs if-else-if-else

c - 将 37.1-28.75 浮点计算正确舍入为 8.4 而不是 8.3

c - 二进制 I/O,在文件中查找要修改的特定字节