问题描述
我正在尝试制作一个字计数器程序,并希望在没有额外空间的情况下为字符串动态分配内存。到目前为止,这是我的代码:
#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 个字节的内存,直到字符串正好适合?我做错了什么?
解决方法
在您的职能中:
char *strmalloc(char *string) {
===> char *strmalloc(char **string) {
tmp = realloc(string,size);
===> tmp = realloc(*string,size);
string = NULL;
===> *string = NULL;
string = tmp;
===> *string = tmp
;
string[index++] = ch;
===> (*string)[index++] = ch;
return string;
===> return *string;
在调用函数中:
strmalloc(user_input);
===> strmalloc(&user_input);