-4

我的程序需要两个命令行输入,stock.csv并且coins.csv. 在我的程序开始附近,我load_check = load_data(&tm, argv[1], argv[2]);将文件初始化为链表。问题是,不知何故,这行代码正在改变argv[1]to的值d,但argv[2]仍然是coins.csv。我真的很困惑是什么原因造成的,这真的很奇怪。有任何想法吗?

编辑:抱歉响应缓慢,发现代码的另一个问题并正在修复它。代码load_data(现在将argv[1] 更改为""

BOOLEAN load_data(tm_type * tm, char * stockfile, char * coinsfile)
{
stock_node *sstream = NULL;
char* token;
char line_no[LINE_LENGTH + 1], *ptr;
FILE *sfile, *cfile;
BOOLEAN check = TRUE;
int denom = 0;

if((sfile = fopen(stockfile, "r")) == NULL){

    fprintf(stderr, "Error in %s.\n", stockfile);
    check = FALSE;

}

if((cfile = fopen(coinsfile, "r")) == NULL){

    fprintf(stderr, "Error in %s.\n", coinsfile);
    check = FALSE;

}

sstream = tm -> stock -> head_stock;

while(fgets(line_no, LINE_LENGTH + 1, sfile) != NULL){

    sstream = malloc(sizeof(tm -> stock));
    sstream -> data = malloc(sizeof(struct stock_data));
    token = strtok(line_no, ",");
    strcpy(sstream -> data -> ticket_name, token);
    token = strtok(NULL, ",");
    sstream -> data -> ticket_type = token[0];
    token = strtok(NULL, ",");
    strcpy(sstream -> data -> ticket_zone, token);
    token = strtok(NULL, ",");
    sstream -> data -> ticket_price = strtol(token, &ptr, 10);
    token = strtok(NULL, ",");
    sstream -> data -> stock_level = strtol(token, &ptr, 10);
    sstream -> next_node = tm -> stock -> head_stock;
    tm -> stock -> head_stock = sstream;

}

while(fgets(line_no, LINE_LENGTH + 1, cfile) != NULL){

    token = strtok(line_no, ",");
    tm -> coins[denom].denomination = strtol(token, &ptr, 01);
    token = strtok(NULL, ",");
    tm -> coins[denom].count = strtol(token, &ptr, 10);
    denom++;

}

return check;
}

变量变化发生在第五次迭代中

while(fgets(line_no, LINE_LENGTH + 1, cfile) != NULL){

    token = strtok(line_no, ",");
    tm -> coins[denom].denomination = strtol(token, &ptr, 01);
    token = strtok(NULL, ",");
    tm -> coins[denom].count = strtol(token, &ptr, 10);
    denom++;

}

另外,tm -> coins[denom].denomination = strtol(token, &ptr, 01);给我一个warning: Invalid parameter passed to C runtime function.错误,但似乎并没有以任何其他方式影响代码。

定义:(这些是预先提供的启动代码,这是一个类)

typedef struct stock_list * stock_list_ptr;
typedef struct coin * coin_list_ptr;
typedef struct tm
{
coin_list_ptr coins;
stock_list_ptr stock;
} tm_type;

struct stock_data 
{
char ticket_name[TICKET_NAME_LEN+1];
char ticket_type;
char ticket_zone[TICKET_ZONE_LEN+1];
unsigned int ticket_price;
unsigned int stock_level;
};
typedef struct stock_node 
{
struct stock_data * data;
struct stock_node * next_node;
} stock_node;

struct stock_list
{
stock_node * head_stock;
unsigned int num_stock_items;
};
4

1 回答 1

0

为什么不将签名更改为:

BOOLEAN load_data(tm_type * tm, const char * stockfile, const char * coinsfile)

这样,您可以确保 load_data 不会修改 argv[1] 和 argv[2] 指向的数据。但这并不能解决你的问题。

注册警告,

tm -> coins[denom].denomination = strtol(token, &ptr, 01);

01 是错字还是面额只有 2 个值的枚举?

此外,初始化指针和关闭文件句柄也很重要。

于 2013-10-13T10:21:22.423 回答