gpt4 book ai didi

c - C语言中使用getchar()读取输入时是否需要分配内存?

转载 作者:行者123 更新时间:2023-11-30 14:47:28 24 4
gpt4 key购买 nike

在下面的代码中,是否应该使用诸如 malloc() 之类的函数为指针 c 分配内存?我担心递增 c 可能会导致它指向另一个变量,从而在调用 *c = getchar() 时覆盖它。

char *c;
int count = 0;

while( (*c=getchar()) != '\n' ){
c++;
count++;
}

最佳答案

发布的代码有问题:

  • c未初始化,写入它会立即产生未定义的行为,增加它只会使情况变得更糟。
  • 您不测试文件结尾,也不测试任何数组边界,因此即使 c被设置为指向一个实际的数组,静态的、自动的或动态地从堆中分配 malloc() ,您必须检查 c保持在该数组的边界内。

这是更正后的版本:

#include <stdio.h>

int main() {
char buf[100];
int c, count, limit;
char *p;

p = buf; /* p points to an automatic array, no malloc needed */
count = 0;
limit = sizeof(buf) - 1; /* maximum number of characters to store */

while ((c = getchar()) != EOF && c != '\n') {
if (count < limit)
*p++ = c;
count++;
}
if (count < limit)
*p = '\0';
else
buf[limit] = '\0';

printf("%s\n", buf);
return 0;
}

这是一个内存分配的例子:

#include <stdio.h>
#include <stdlib.h>

int main() {
char *buf, *p;
int c, count, limit;

limit = 99;
p = buf = malloc(limit + 1); /* p points to an array allocated from the heap */
count = 0;

if (buf == NULL) {
printf("allocation failure\n");
return 1;
}

while ((c = getchar()) != EOF && c != '\n') {
if (count < limit)
*p++ = c;
count++;
}
if (count < limit)
*p = '\0';
else
buf[limit] = '\0';

printf("%s\n", buf);
free(buf);
return 0;
}

注释:

  • while ((c = getchar()) != EOF && c != '\n')是一个经典的 C 习惯用法,用于从标准输入读取一个字节,并将其存储在 int 中。变量c ,检查文件末尾并检查单个控制表达式中的行尾。 &&首先评估其左侧,并且仅在结果为 bool 值 0 时评估其右侧或1类型 int ,无法从左侧的值确定。这种特性称为快捷方式评估,适用于 ||和三元运算符 ?/:也是。
  • c必须具有可以容纳 getchar() 返回的所有值的类型:类型 unsigned char 的所有值和特殊负值EOF 。两者都不是char也不signed char也不unsigned char适合于此,如 c == EOF会错误地匹配 \377 (ISO-8859-1 中的 'ÿ')用于签名的 char大小写或从不匹配未签名的 char案件。 intc 的正确类型.

关于c - C语言中使用getchar()读取输入时是否需要分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223260/

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