我想寫一個包裝從文件中取一些預定義的標準輸入。如果開頭有'#',程序應該跳過一行,否則將除了前2個元素之外的所有元素存儲在稱爲factorList的數組中。 我正在使用malloc來動態分配內存到這個指針。 我然後試圖訪問這個數組之外的while循環,我聲明它,但它導致一個錯誤。malloc內存無法訪問外循環
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
int main(int argc, char * argv[])
{
int degree = 100;
int tempDegree;
int num;
int * factorList;
FILE * primeFile = fopen(argv[1],"r");
if(!primeFile)
{
printf("Could not open file containing prime table\n");
}
char store[100] = {0};
char lineCheck = ' ';
int primeCheck = fscanf(primeFile, "%s", store);
while(primeCheck != EOF)
{
if(strcmp("#",store) == 0)
{
printf("Mark1\n");
// Clearing Store array
memset(store, 0 , sizeof(store));
// Skip this line
while((lineCheck != '\n') && (primeCheck != EOF))
{
primeCheck = fscanf(primeFile, "%c", &lineCheck);
}
lineCheck = ' ';
// Reading the start of the next line
if(primeCheck != EOF)
{
primeCheck = fscanf(primeFile, "%s", store);
}
}
else
{
tempDegree = atoi(store);
if(tempDegree == degree)
{
printf("Mark2\n");
// This is the list of primes
primeCheck = fscanf(primeFile, "%d", &num);
factorList = malloc(sizeof(int)*num);
int i;
for(i=0;i < num; i++)
{
primeCheck = fscanf(primeFile, "%d", &factorList[i]);
printf("%d",factorList[i]);
}
break;
}
else
{
printf("Mark3\n");
// Clearing Store array
memset(store, 0 , sizeof(store));
// Skip this line
while((lineCheck != '\n') && (primeCheck != EOF))
{
primeCheck = fscanf(primeFile, "%c", &lineCheck);
}
lineCheck = ' ';
// Reading the start of the next line
if(primeCheck != EOF)
{
primeCheck = fscanf(primeFile, "%s", store);
}
}
}
// Testing Access to factorList , getting error here.
int i = factorList[0];
}
return 0;
}
'strcmp(「#」,store)== 0'將檢查整行是否正好是'#'...不只是第一個字符。改爲使用'store [0] =='#''。 – 2015-01-21 03:53:43
它僅在一個條件上分配,在其他情況下,該列表將爲NULL,在訪問它之前檢查NULL – radar 2015-01-21 03:53:59
您的循環非常複雜;而不是在循環之前讀取第一行,並讓循環中的每條代碼路徑讀取下一行的開始,您應該在循環的開始處讀取行的開始(並且如果出現錯誤,break; '出)。 – 2015-01-21 03:55:09