gpt4 book ai didi

c - 空指针和动态内存分配

转载 作者:行者123 更新时间:2023-12-04 08:17:45 27 4
gpt4 key购买 nike

我正在尝试制作一个单词计数器程序,它需要一个句子并计算单词的数量。我想使用动态内存分配,因为它有很多优点,例如不必担心空间不足或空余空间过多。到目前为止,这是我的代码:

#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 函数的原型(prototype)是这样的:
void *realloc(void *ptr, size_t size)
当我在 strmalloc() 的 while 循环中使用 realloc 函数时功能,我收到警告说:
Passing 'const char *' to parameter of type 'void *' discards qualifiers
我不知道这意味着什么,但我知道我可以通过类型转换为 char* 来摆脱它。
但是,我了解到我不应该仅仅为了防止警告而使用类型转换。我应该了解警告警告我的内容,并确定类型转换是否正确。但是话又说回来,我知道指向 void 的指针可以接受任何数据类型,并且要指定一个,需要进行类型转换。所以我的问题是,我应该将类型转换保留在 realloc() 中吗?发挥作用或摆脱它并做其他事情。

最佳答案

const是一个类型限定符。在 C也许在许多其他编程语言中,const应用于数据类型表示该数据是只读的。

Passing 'const char *' to parameter of type 'void *' discards qualifiers


您收到上述错误是因为您正在传递 const对象不是 const 的参数( (void *) 中的 realloc ),并警告您可能会更改(丢弃) const char* string 指向的值通过使用 void* ptr ,这违背了将数据声明为 const 的全部目的.
但是看这个例子,你正试图为 char* string 分配内存。 ,并且在分配之后,如果你把它写成 const,你会想要在那个内存中写入一些东西。 ,期待它怎么写。
所以你不需要你的 char* string成为 const因此,不需要强制转换为 char*realloc .

关于c - 空指针和动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65639593/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com