首页 > 解决方案 > Issue when using pointer to line tokens in C

问题描述

I have created a program that requires reading a CSV file that contains bank accounts and transaction history. To access certain information, I have a function getfield which reads each line token by token:

const char* getfield(char* line, int num)
{
    const char *tok;
    for (tok = strtok(line, ",");
            tok && *tok;
            tok = strtok(NULL, ",\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

I use this later on in my code to access the account number (at position 2) and the transaction amount(position 4):

...
while (fgets(line, 1024, fp))
{


        char* tmp = strdup(line); 

        //check if account number already exists

        char *acc = (char*) getfield(tmp, 2); 
        char *txAmount = (char*)getfield(tmp, 4);

        printf("%s\n", txAmount);
        //int n =1;
        if (acc!=NULL && atoi(acc)== accNum && txAmount !=NULL){
                if(n<fileSize)
                {
                        total[n]= (total[n-1]+atof(txAmount));
                        printf("%f", total[n]);
                        n++;

                }

         }
         free(tmp1); free(tmp2);
}
...

No issue seems to arise with char *acc = (char*) getfield(tmp, 2), but when I use getfield for char *txAmount = (char*)getfield(tmp, 4) the print statement that follows shows me that I always have NULL. For context, the file currently reads as (first line is empty):


AC,1024,John Doe
TX,1024,2020-02-12,334.519989
TX,1024,2020-02-12,334.519989
TX,1024,2020-02-12,334.519989

I had previously asked if it was required to use free(acc) in a separate part of my code (Free() pointer error while casting from const char*) and the answer seemed to be no, but I'm hoping this question gives better context. Is this a problem with not freeing up txAmount? Any help is greatly appreciated !

(Also, if anyone has a better suggestion for the title, please let me know how I could have better worded it, I'm pretty new to stack overflow)

标签: cpointersconstantsfree

解决方案


问题是 strtok 将找到的分隔符替换为'\0'. 您需要获得该行的新副本。
或者继续你离开的地方,使用getfield (NULL, 2).


推荐阅读