【发布时间】:2021-08-17 18:06:13
【问题描述】:
我想在这里做的是,我想用 scanf 将用户的输入读入 char 指针,并在读取更多输入时动态分配内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *ptr, temp;
int i, ind = 0;
ptr = malloc(sizeof(char) * 2);
while (scanf(" %[^\n]c", &temp) != EOF)
{
ptr[ind] = temp;
ind++;
ptr = realloc(ptr, sizeof(char) * (ind + 1));
}
for (i = 0; i < 5; i++)
printf("%c", *(ptr + i));
return 0;
}
我的代码是这样的,但是它要么引发分段错误(当一行中的字符数超过 8 个时),要么甚至不打印任何字符。我错过了什么?提前致谢。
【问题讨论】:
-
2 * sizeof(char)并没有完全按照你的想法做,你只为 2 个字符分配内存。 -
@alex01011:他们就是这么想的。它们以两个字符开头,并使用
realloc来读取更多字符。 -
@EricPostpischil 那么
scanf()是错误的函数:) -
至少是那种形式
-
这就是 scanf 的
m标志的用途:scanf("% m[^\n]", &ptr);
标签: c scanf dynamic-memory-allocation