gpt4 book ai didi

C 程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 05:25:53 24 4
gpt4 key购买 nike

您好,我需要一些帮助来调试我的程序:它应该从控制台读取、处理输入并将其返回:

第二次调用 while(scanf("%15s", input) != EOF) 后发生错误。不幸的是我不能告诉你错误是什么,因为程序卡住并且没有给我任何信息。我认为 input var 有问题(它被多次传递)

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

char* repeat(char c, int n);
char* drawLabel(char* label, int n);
char* drawBarnorm(char* label, int value);
char* drawBar(char* label, double value);

int main(void)
{
char* input;
double numIn;
char buf[] = "";
char* pOutput = &buf[0];

while(scanf("%15s", input) != EOF)
{
scanf("%lf", &numIn);
if (numIn > 1)
{
if (numIn > 30)
{
printf("num to big!\n");
return 0;
}

strcat(pOutput, drawBarnorm(input, (int)numIn));
} else
{strcat(pOutput, drawBar(input, numIn));}


printf("%s\n", pOutput);
}

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

char* repeat(char c, int n)
{
char* out = (char*)malloc(sizeof(char)*50);
int i, len;
out[0] = '\0';

for (i = 0; i < n; ++i)
{
len = strlen(out);
out[len] = c;
out[len+1] = '\0';
}

return out;
}

char* drawLabel(char* label, int n)
{
if (strlen(label) > n)
{
char* newLabel = (char*)malloc(sizeof(char)*(n+1));
newLabel[0] = '\0';
strncpy(newLabel, label, n);
newLabel[n] = '\0';
return newLabel;
} else if (strlen(label) < n)
{
strcat(label, repeat(' ', n-strlen(label)));
}

return label;
}

char* drawBarnorm(char* label, int value)
{
char* bar = (char*)malloc(sizeof(char)*41);
char* barPart;
bar[0] = '\0';
bar = drawLabel(label, 8);
strcat(bar, "|");
barPart = drawLabel(repeat('#', value), 30);
strcat(bar, barPart);
strcat(bar, "|");
return bar;
}

char* drawBar(char* label, double value)
{
int val = (int)(30.0*value);
return drawBarnorm(label, val);
}

谢谢你帮我解决这个问题。

最佳答案

char* input = malloc(size); /* Allocate memory of your wish */

分配内存给input 你还没有初始化你的指针。

指针应该指向某个有效的内存位置,以通过 scanf()

存储值

关于C 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27846047/

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