我想写一个包装从文件中取一些预定义的标准输入。如果开头有'#',程序应该跳过一行,否则将除了前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