我遇到了一個問題,即在用於從文件中讀取內容的循環外部時,我的數組不能正確打印。代碼如下所示:C陣列正確地在循環外打印
int main(int argc, char **argv)
{
char *fileArray[78];
int i, j;
DIR *d;
struct dirent *dir;
char arra[128][128];
char *arra1[14284][128];
char line[1024];
char line1[1024];
char noiseList[128][128];
char *noiseList1[14][128];
char *token;
char *token1;
char *path = "./alerts2013/2013/";
char *path1 = "./Noise_and_Concepts/";
char *fileName;
char *fileName1;
char seps[] = " ,\t\n";
FILE *myfile;
FILE *noise;
int size = 0;
d = opendir("./alerts2013/2013");
fileName1 = stradd(path1, "noise.txt");
//printf("%s\n", fileName1);
noise = fopen(fileName1, "r");
if (noise == 0)
{
printf("can not open file \n");
exit(1);
}
int a, b;
for(a = 0; a < 128; a++) {
line[a] = '\0';
}
for(a = 0; a < 128; a++) {
for(b = 0; b < 128; b++) {
noiseList[a][b] = '\0';
noiseList1[a][b] = '\0';
arra[a][b] = '\0';
arra1[a][b] = '\0';
}
}
i = 0;
j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int q;
int r;
while(fgets(line, sizeof(line), noise) != NULL) {
strcpy(noiseList[k], line);
//printf("%s", noiseList[k]);
token = strtok(noiseList[k], seps);
while(token != NULL)
{
/* While there are tokens in "string" */
//printf("%s\n", token);
//printf("array ----> %s\n", token);
lower_string(token);
noiseList1[n][0] = token;
n++;
/* Get next token: */
token = strtok(NULL, seps);
}
k++;
}
if (d)
{
while ((dir = readdir(d)) != NULL)
{
fileArray[i] = dir->d_name;
//printf("%s\n", fileArray[i]);
fileName = stradd(path, dir->d_name);
//printf("%s\n", fileName);
free(fileName);
myfile = fopen(fileName,"r");
if (myfile == 0)
{
printf("can not open file \n");
exit(1);
}
for(i = 0; i < 128; i++) {
line1[i] = '\0';
}
if(myfile != NULL) {
while(fgets(line1, sizeof(line1), myfile) != NULL) {
strcpy(arra[l], line1);
//printf("Tokens:\n");
/* Establish string and get the first token: */
token = strtok(arra[l], seps);
while(token != NULL)
{
/* While there are tokens in "string" */
//printf("%s\n", token);
//printf("array ----> %s\n", token);
lower_string(token);
arra1[m][0] = token;
printf("Arra1: %s\n", arra1[m][0]); //PRINTING
//CORRECTLY HERE
size++;
m++;
/* Get next token: */
token = strtok(NULL, seps);
}
//printf("array ----> %s ", &arra[i]);
i++;
}
}
fclose(myfile);
i++;
}
closedir(d);
}
int p;
int w;
printf("%d\n", size);
/*for(p = 0; p < 14; p++) {
printf("%s\n", noiseList1[p][0]);
}*/
for(w = 0; w < size; w++) { //PRINTING INCORRECTLY HERE
printf("Arr1 (final): %s\n", arra1[w][0]);
}
fclose(noise);
return(0)
}
在第一次printf語句中沒有註釋,數組打印正確。但是,在代碼底部的for循環中沒有註釋,它會截斷數組中字符串的一些字母。例如,未認證可能會成爲認證。我不知道爲什麼會發生這種情況。我不認爲我的數組正在保存正確,但我不完全確定。我將如何解決這個問題?
char * arra1 [14284] [128];':這似乎很大,以確保在堆棧上。 – BLUEPIXY
這是很大的,因爲我需要逐字閱讀文件的數量。當我跑完櫃檯看到總共有多少個單詞時,14284被彈出。 – zackster7171
'free(fileName); myfile = fopen(fileName,「r」);'不管它是什麼都是壞消息。 – aschepler