给定以下函数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/