【发布时间】:2018-09-25 05:28:05
【问题描述】:
Windows NT 崩溃了。 我是蓝屏死机。 没有人听到你的尖叫声。
我正在编写一个程序,我必须从文件中读取俳句,之后我必须将所有五个音节行存储到一个数组中,并将所有七个音节行存储到另一个数组中。我必须使用一个 char* 指针数组来存储每组行。我也只能在每个指针处为字符串的实际长度分配足够的空间。因此,对于上面的俳句,我应该分别为这三行分配 20、31 和 28 个字节(包括 \0)。 从文件中读入所有行并将其存储到适当的数组中后,我必须使用随机数生成器来选择一组三行以打印到屏幕上。
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("This number of arguments is incorrect.");
return 1;
}
FILE *oldfile, *newfile;
char const *newfilename = "myhaiku.txt";
int linecntr = 0, fivesyllines = 0, svnsyllines = 0;
int freearr, newhaiku;
// char **fivesylptrs = malloc(200 * sizeof(char *));
// char **svnsylptrs = malloc(200 * sizeof(char *));
char *fivesylptrs[200], *svnsylptrs[100];
char line[129];
srand(time(NULL));
/* for (fivesyllines = 0; fivesyllines < 200; fivesyllines++)
{
fivesylptrs[fivesyllines] = (char *) malloc(129 * sizeof(char));
}
for (svnsyllines = 0; svnsyllines < 200; svnsyllines++)
{
svnsylptrs[svnsyllines] = (char *) malloc(129 * sizeof(char));
} */
oldfile = fopen(argv[1], "r");
newfile = fopen(newfilename, "w");
if (oldfile)
{
while (fgets(line, 129, oldfile) != NULL)
{
linecntr++;
if ((linecntr % 2) != 0)
{
// printf("%s", line);
fivesylptrs[fivesyllines] = (char *)malloc(129 * sizeof(char));
if (fivesylptrs[fivesyllines] == NULL)
{
printf("The memory for the five syllable strings wasn't allocated properly.\n");
}
strcpy(fivesylptrs[fivesyllines], line);
// printf("%s", fivesylptrs[fivesyllines]);
fivesylptrs[fivesyllines] = fivesylptrs[fivesyllines + 1];
// fivesyllines++;
}
else if ((linecntr % 2) == 0 && line[0] != '\n')
{
// printf("%s", line);
svnsylptrs[svnsyllines] = (char *)malloc(129 * sizeof(char));
if (svnsylptrs[svnsyllines] == NULL)
{
printf("The memory for the seven syllable strings wasn't allocated properly.\n");
}
strcpy(svnsylptrs[svnsyllines], line);
// printf("%s", svnsylptrs[svnsyllines]);
svnsylptrs[svnsyllines] = svnsylptrs[svnsyllines + 1];
// svnsyllines++;
}
}
}
else
{
printf("This file could not be opened, please try again.\n");
}
for (newhaiku = 0; newhaiku < 10; newhaiku++)
{
printf("%s", fivesylptrs[(rand() % 200)]);
printf("%s", svnsylptrs[(rand() % 100)]);
printf("%s", fivesylptrs[(rand() % 200)]);
}
fclose(oldfile);
fclose(newfile);
for (freearr = 0; freearr < 200; freearr++)
{
free(fivesylptrs[freearr]);
}
for (freearr = 0; freearr < 100; freearr++)
{
free(svnsylptrs[freearr]);
}
return 0;
}
我已经尝试了很多不同的技术来解决我很确定我在使用 malloc 时遇到的错误,但我无法弄清楚我做错了什么。我非常感谢任何和所有的帮助!
【问题讨论】:
-
取消注释这些 for 循环时是否会发生崩溃?
-
fivesyllines未递增。 -
@Sandeep 是否做五色线[五色线] = 五色线 [五色线 + 1];不增加五行?
-
@rafix07 我不明白你在说什么,你能澄清一下吗?
-
@P.W 是的,当我取消注释这两个循环时,程序关闭而不返回任何内容。
标签: c memory-management malloc