作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我编写了这段代码,但在字符串的开头插入了垃圾:
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/
我是一名优秀的程序员,十分优秀!