【问题标题】:C variable changes in loop循环中的 C 变量更改
【发布时间】:2018-03-22 10:05:56
【问题描述】:

当尝试遍历文件中的行并获取其中的数字时,我使用了以下代码,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

【问题讨论】:

  • 问题/疑问是什么?

标签: c loops variables fgets


【解决方案1】:

strspl 被声明为 1 大小的字符数组(仅以 null 结尾)。在其中复制超过 1 个字符会调用未定义行为(因为您在内存中写入其他变量可以使用)。从那时起,一切皆有可能......

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

#define SIZE 1024

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

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

【讨论】:

  • 谢谢!!!我觉得我之前没有尝试过这个。但现在一切正常。
猜你喜欢
  • 2013-09-13
  • 2011-02-19
  • 1970-01-01
  • 2011-07-14
  • 2019-10-08
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多