空指针和动态内存分配
Void pointers and dynamic memory allocation
我正在尝试制作一个单词计数器程序,它接受一个句子并计算单词的数量。我想使用动态内存分配,因为它有很多优点,例如不必担心 space 不足或空太多 space。到目前为止,这是我的代码:
#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()
函数中还是摆脱它并做其他事情。
const
是类型限定符。在 C
以及许多其他编程语言中,应用于数据类型的 const
表示数据是只读的。
Passing 'const char *' to parameter of type 'void *' discards qualifiers
您收到上述错误是因为您将 const
对象传递给不是 const
的参数(realloc
中的 (void *)
),并警告您有关有可能通过使用 void* ptr
更改(丢弃)const char* string
指向的值,这违背了将数据声明为 const
.
的整个目的
但是看看这个例子,你正在尝试为 char* string
分配内存,并且在分配之后,你会想要向该内存中写入一些东西,如果你做到了 const
,如何期待它写。
因此您不需要将 char* string
设为 const
,因此,无需在 realloc
.[=27= 中强制转换为 char*
]
我正在尝试制作一个单词计数器程序,它接受一个句子并计算单词的数量。我想使用动态内存分配,因为它有很多优点,例如不必担心 space 不足或空太多 space。到目前为止,这是我的代码:
#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()
函数中还是摆脱它并做其他事情。
const
是类型限定符。在 C
以及许多其他编程语言中,应用于数据类型的 const
表示数据是只读的。
Passing 'const char *' to parameter of type 'void *' discards qualifiers
您收到上述错误是因为您将 const
对象传递给不是 const
的参数(realloc
中的 (void *)
),并警告您有关有可能通过使用 void* ptr
更改(丢弃)const char* string
指向的值,这违背了将数据声明为 const
.
但是看看这个例子,你正在尝试为 char* string
分配内存,并且在分配之后,你会想要向该内存中写入一些东西,如果你做到了 const
,如何期待它写。
因此您不需要将 char* string
设为 const
,因此,无需在 realloc
.[=27= 中强制转换为 char*
]