我正在尝试制作一个单词计数器程序,并希望在没有额外空间的情况下为字符串动态分配内存。到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
char *strmalloc(char *string);
char *user_input = NULL;
int main(void) {
printf("Enter a sentence to find out the number of words: ");
strmalloc(user_input);
printf("You entered %s", user_input);
return 0;
}
char *strmalloc(char *string) {
char *tmp = NULL;
size_t size = 0, index = 0;
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (size <= index) {
size += 1;
tmp = realloc(string, size);
if (!tmp) {
free(string);
string = NULL;
break;
}
string = tmp;
}
string[index++] = ch;
}
return string;
}
这是输出:
Enter a sentence to find out the number of words: Testing program
You entered (null)
Process finished with exit code 0
我认为在 while 循环中,我重新分配了 1 个字节的内存,直到字符串正好合适?我究竟做错了什么?