【发布时间】:2021-01-09 05:19:39
【问题描述】:
我正在尝试制作一个单词计数器程序,它需要一个句子并计算单词的数量。我想使用动态内存分配,因为它有许多优点,例如不必担心空间不足或空余空间过多。到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
const char *strmalloc(const char *string);
char *user_input = NULL;
int main(void) {
printf("Enter a sentence to find out the number of words: ");
strmalloc(user_input);
return 0;
}
const char *strmalloc(const 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((char*)string, size);
}
}
}
您可能知道,realloc 函数的原型是这样的:
void *realloc(void *ptr, size_t size)
当我在 strmalloc() 函数的 while 循环中使用 realloc 函数时,我收到一条警告:
Passing 'const char *' to parameter of type 'void *' discards qualifiers
我不知道这意味着什么,但我知道我可以通过对char* 的类型转换来摆脱它
但是,我了解到我不应该仅仅为了防止警告而使用类型转换。我应该了解警告警告我的内容,并确定类型转换是否正确。但话又说回来,我知道指向 void 的指针可以接受任何数据类型,并且要指定一个,需要进行类型转换。所以我的问题是,我应该将类型转换保留在 realloc() 函数中还是去掉它并做其他事情。
【问题讨论】:
-
A qualifier 是修改类型的关键字,例如
volatile或const。这有帮助吗? -
@JohnKugelman 感谢您回答问题的那一部分,但我的主要问题仍未得到解答。如果你知道答案,请告诉我。谢谢!
-
它将引导您找到正确的答案。你想避免抛弃警告是正确的。有比抛弃
const更好的解决方案。 -
@JohnKugelman,对不起,我想我不明白。你能告诉我你在做什么吗?
-
Do not cast away a const qualification.
remove_spaces示例与您的代码非常相似。
标签: c memory-management