gpt4 book ai didi

c - 如何在 C 中将字符追加到动态分配内存的字符串中?

转载 作者:行者123 更新时间:2023-12-01 17:16:25 26 4
gpt4 key购买 nike

我编写了这段代码,但在字符串的开头插入了垃圾:

void append(char *s, char c) {
int len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}

int main(void) {
char c, *s;
int i = 0;
s = malloc(sizeof(char));
while ((c = getchar()) != '\n') {
i++;
s = realloc(s, i * sizeof(char));
append(s, c);
}
printf("\n%s",s);
}

我该怎么做?

最佳答案

您的代码中存在多个问题:

  • 进行迭代,直到从标准输入流中读取换行符 ('\n')。如果在读取换行符之前发生文件结尾,这将导致无限循环,如果从空文件重定向标准输入,就会发生这种情况。
  • c 应定义为 int,以便您可以正确测试 EOF
  • s 应始终以 null 终止,您必须将 malloc() 之后的第一个字节设置为 '\0',如下所示函数不会初始化它分配的内存。
  • i 应初始化为 1,因此第一个 realloc() 将数组扩展 1 等。按照编码,您的数组是一个字节太短,无法容纳额外的字符。
  • 您应该检查内存分配是否失败。
  • 为了保持良好的风格,您应该在退出程序之前释放分配的内存
  • main() 应返回一个 int,最好是 0 以表示成功。

这是更正后的版本:

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

/* append a character to a string, assuming s points to an array with enough space */
void append(char *s, char c) {
size_t len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}

int main(void) {
int c;
char *s;
size_t i = 1;
s = malloc(i * sizeof(char));
if (s == NULL) {
printf("memory allocation failure\n");
return 1;
}
*s = '\0';
while ((c = getchar()) != EOF && c != '\n') {
i++;
s = realloc(s, i * sizeof(char));
if (s == NULL) {
printf("memory allocation failure\n");
return 1;
}
append(s, c);
}
printf("%s\n", s);
free(s);
return 0;
}

关于c - 如何在 C 中将字符追加到动态分配内存的字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52596885/

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