为什么我使用C中的指针从stdin得到错误的动态长度字符串?

为什么我使用C中的指针从stdin得到错误的动态长度字符串?,c,C,我试图通过指针和realloc()函数在C中接收一个长度未知的字符串,但在该字符串变为30个字符长后,前几个字符如下所示: ÿZ └ 我正在windows上运行它: #include <stdio.h> #include <stdlib.h> char* array; int current = 0; int size = 10; void add(char element) { if (current == size) { size +=

我试图通过指针和realloc()函数在C中接收一个长度未知的字符串,但在该字符串变为30个字符长后,前几个字符如下所示:

ÿZ └ 
我正在windows上运行它:

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

char* array;
int current = 0;
int size = 10;

void add(char element)
{
    if (current == size) {
        size += 10;
        realloc(array, size * (sizeof(char)));
    }
    *(array + current) = element;
    current++;
}

int main()
{
    array = calloc(10, sizeof(char));
    char c;
loop:
    c = getchar();
    if (c != '\n') {
        add(c);
        goto loop;
    }
    else {
        for (int i = 0; i <= current - 1; i++) {
            putchar(*(array + i));
        }
        printf("\nThe size of the string is %d", current);
    }
}
#包括
#包括
字符*数组;
int电流=0;
int size=10;
void添加(char元素)
{
如果(当前==大小){
尺寸+=10;
realloc(数组,大小*(sizeof(char));
}
*(数组+电流)=元件;
电流++;
}
int main()
{
数组=calloc(10,sizeof(char));
字符c;
循环:
c=getchar();
如果(c!='\n'){
添加(c);
后藤环;
}
否则{

对于(int i=0;i您需要这样做:

array=realloc(array,size*(sizeof(char)));
内存可能会移动到另一个位置。这就是为什么需要重新分配指针

当然,也可以进行一些错误检查:

char *tmp;
tmp = realloc(array,size*(sizeof(char)));
if(tmp) 
    array=tmp;
else
    perror("realloc failed");

您需要这样做:

array=realloc(array,size*(sizeof(char)));
内存可能会移动到另一个位置。这就是为什么需要重新分配指针

当然,也可以进行一些错误检查:

char *tmp;
tmp = realloc(array,size*(sizeof(char)));
if(tmp) 
    array=tmp;
else
    perror("realloc failed");

您没有存储
realloc
的返回值

char *temp;
temp=realloc(array,size*(sizeof(char)));

if( temp )
  array = temp;
else
  // error
goto
通过生成复杂的控制流,使代码更难调试

如果您这样想,您将看到您可以用
for
while
循环替换
转到

您可以看到您的else部分不是
goto
部分的一部分。一旦执行了
else
,它就再也不会执行了

因此,在循环外部创建一个循环(
else
part)


另外,
getchar()
的返回类型是
int

您没有存储
realloc
的返回值

char *temp;
temp=realloc(array,size*(sizeof(char)));

if( temp )
  array = temp;
else
  // error
goto
通过生成复杂的控制流,使代码更难调试

如果您这样想,您将看到您可以用
for
while
循环替换
转到

您可以看到您的else部分不是
goto
部分的一部分。一旦执行了
else
,它就再也不会执行了

因此,在循环外部创建一个循环(
else
part)


另外,
getchar()
的返回类型是
int

不存储
realloc
的返回值。首先,返回新指针。不要使用
goto
进行循环。使用正确的循环。今天在“为什么你应该阅读文档”中。或者只是想一想。
realloc
…重新分配,对吗?那么,除非你以某种方式从中获取一些信息,否则你怎么知道它已重新分配到哪里?抱歉,但此代码必须从头重写。不要使用全局变量。不要无条件地向上分支。getchar()返回int。realloc的使用完全是错误的。以此类推。如果不首先存储realloc的返回值,则返回(可能)新指针。不要使用
goto
进行循环。使用正确的循环。今天在“为什么你应该阅读文档”中。或者只是想一想。
realloc
…重新分配,对吗?那么,除非你以某种方式从中获取一些信息,否则你怎么知道它已重新分配到哪里?抱歉,但此代码必须从头重写。不要使用全局变量。不要无条件地向上分支。getchar()返回int。realloc的使用完全错误。以此类推。