Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 循环中的变量变化_C_Loops_Variables_Fgets - Fatal编程技术网

C 循环中的变量变化

C 循环中的变量变化,c,loops,variables,fgets,C,Loops,Variables,Fgets,在尝试循环文件中的行并获取其中的数字时,我使用了以下代码,lnCount(用于循环中的增量)的值在循环的第一次迭代后更改: long nbl = nbLine(filename); // This function works fine long *allocatedMemoryStartingPos = NULL; allocatedMemoryStartingPos = malloc(sizeof(long)*(nbl+1)); if (allocatedMemoryStarting

在尝试循环文件中的行并获取其中的数字时,我使用了以下代码,
lnCount
(用于循环中的增量)的值在循环的第一次迭代后更改:

long nbl = nbLine(filename); // This function works fine

long *allocatedMemoryStartingPos = NULL; 
allocatedMemoryStartingPos = malloc(sizeof(long)*(nbl+1)); 

if (allocatedMemoryStartingPos == NULL) {
    exit(0); // Immediately stops the program
}

long *posPtr = &allocatedMemoryStartingPos[0];

initArrayTo0(allocatedMemoryStartingPos, nbl+1); // Works as well, sets all values 0

char str[] = "";
char spl[] = "";
long val = 0;

FILE* f = NULL;
f = fopen(filename, "r");
if (f != NULL) {
    for (long lnCount = 0; lnCount < nbl; lnCount++) {
        printf("lnCount = %ld\n", lnCount);
        getStartPosFromFile(f, 250, &val, str, spl);
        posPtr = val;
        posPtr++;
    }
}
fclose(f);
free(allocatedMemoryStartingPos);
在上面的代码中,extractColumn也可以正常工作,它只需获取当前行的子字符串并将其复制到
字符串中(
spl

此代码的输出如下所示:

void getStartPosFromFile(FILE* f, int maxSize, long *ret, char str[], char spl[]){
    if (fgets(str, maxSize, f) != NULL) {
        strcpy(spl, extractColumn(str, 7));
        *ret = strtol(spl, NULL, 10);
    } else {
        printf("fgets failed!\n");
        perror("fgets failed!");
    }
}
lncount = 0
lncount = 3301218

str
spl
声明为1大小的字符数组(仅终止为null)。在它们中复制超过1个字符会调用未定义的行为(因为您在内存中写入其他变量可以使用的内容)。从那时起,一切都是可能的

您必须声明符合您需求的尺寸:

#define SIZE 1024

char str[SIZE] = "";
char spl[SIZE] = "";

请输入相关值,而不是我的1024个示例

问题是什么?谢谢!!!我觉得以前没试过。但现在一切正常。