首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换malloc

替换malloc
EN

Stack Overflow用户
提问于 2019-09-27 12:45:32
回答 1查看 87关注 0票数 0

给定以下函数to_lower

代码语言:javascript
复制
#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的情况下执行相同的函数?如果是这样,将如何做到这一点?我正在尝试看看是否可以在不为指针分配新内存的情况下更改指针的“值”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-28 15:51:38

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

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

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58128020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档