循环中的C变量变化
C variable changes in loop
当试图遍历文件中的行并获取其中的数字时,我使用了以下代码,并且 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);
getStartPosFromFile()
的代码如下:
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!");
}
}
在上面的代码中,extractColumn 也可以正常工作,它只是获取当前行的一个子字符串并将其复制到 string
(spl
) 中。
此代码的输出如下:
lncount = 0
lncount = 3301218
str
和 spl
被声明为大小为 1 的字符数组(仅以 null 结尾)。在其中复制超过 1 个字符会调用未定义的行为(因为您在内存中写入可以被其他变量使用)。从那时起,一切皆有可能...
您必须声明符合您需求的尺码:
#define SIZE 1024
char str[SIZE] = "";
char spl[SIZE] = "";
请输入相关值代替我的 1024 示例
当试图遍历文件中的行并获取其中的数字时,我使用了以下代码,并且 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);
getStartPosFromFile()
的代码如下:
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!");
}
}
在上面的代码中,extractColumn 也可以正常工作,它只是获取当前行的一个子字符串并将其复制到 string
(spl
) 中。
此代码的输出如下:
lncount = 0
lncount = 3301218
str
和 spl
被声明为大小为 1 的字符数组(仅以 null 结尾)。在其中复制超过 1 个字符会调用未定义的行为(因为您在内存中写入可以被其他变量使用)。从那时起,一切皆有可能...
您必须声明符合您需求的尺码:
#define SIZE 1024
char str[SIZE] = "";
char spl[SIZE] = "";
请输入相关值代替我的 1024 示例