所以我应该创建完成某项功能: 目的:程序重新洗牌的文本文件洗牌阵列(赛格故障)
- 的行文件读入到一个数组
- 计数线和最大长度
- 计算用于阵列最大宽度
- 获取文件指针到开始
- 预订存储器字符串 的动态数组
- 读取一行并存储在分配的存储器
- 转动\ n为进\ 0
- 打印线从阵列(试验)
- 随机阵列从阵列(试验)
- 打印线
- 免存储器和关闭文件
(只给一些背景)
然而,当我去打印洗牌数组,我得到分段错误。偶尔,它会打印一个或两个字符串,但有时它只是说“Shuffled Array”,然后出现分段错误。有任何想法吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Accepts: command line input
// Returns: 0 if no error
int main(int argc, char *argv[]){
int x = 0, i, lineCount = 0, maxLen = 0;
char line[500], temp;
FILE *file = fopen(argv[1], "r");
// check if file exists
if (file == NULL){
printf("Cannot open file\n");
return 1;
}
// Gets lines, max length of string
while (fgets(line, sizeof(line), file) != NULL){
lineCount++;
if (strlen(line) > maxLen)
maxLen = strlen(line);
}
rewind(file);
char *lineArray[lineCount];
while (fgets(line, sizeof(line), file) != NULL) {
lineArray[x] = malloc(strlen(line));
if (lineArray[x] == NULL){
printf("A memory error occurred.\n");
return(1);
}
strcpy(lineArray[x], line);
// change \n to \0
lineArray[x][strlen(lineArray[x])-1] = '\0';
x++;
}
printf("File %s has %d lines with maximum length of %d characters\n",
argv[1], lineCount, maxLen);
printf("Original Array\n");
for (x = 0; x < lineCount; x++)
printf("%2d %s\n", x, lineArray[x]);
// Shuffle array
srand((unsigned int) time(NULL));
for (x = lineCount - 1; x >= 0; x--){
i = (int) rand() % lineCount;
temp = lineArray[x];
lineArray[x] = lineArray[i];
lineArray[i] = temp;
}
printf("\nShuffled Array\n");
for (x = 0; x < lineCount; x++)
printf("%2d %s\n", x, lineArray[x]);
// free allocated memory
for (x = 0; x < lineCount; x++)
free(lineArray[x]);
free(lineArray);
fclose(file);
return 0;
}
会发生什么,如果你硬编码输入的字符串,而不是试图从文件中读取他们? – Beta
可能重复[文件作为字符串输入到数组中的行](http://stackoverflow.com/questions/19619343/file-input-into-array-by-line-as-string) – Vorsprung
你已经问过这个,去做你的功课 – Vorsprung