gpt4 book ai didi

c - 段错误难题

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:09 25 4
gpt4 key购买 nike

所以我很好奇为什么下面的代码段会出现段错误。在我看来它是正确的。

int * addCoins(char *val){
const char *deli = ",";
char *ptr =NULL;

char *denomination = strtok_r(val, deli, &ptr);
char *count = strtok_r(NULL, deli, &ptr);
int deno = atoi(denomination);
int cnt = atoi(count);
int *k;
k = malloc(sizeof(*k)*2);
k[0] = deno;
k[1] =cnt;

return k;
}

调用 main 中的 addCoins 函数。我不认为问题出在这里,但老实说,我对这个问题有点不知所措。

char* fileNameCoin = argv[2];
FILE *fileCoin;
fileCoin = fopen(fileNameCoin, "r+");
char bufCoin[256];
int i = 0;
//vmNode->next = NULL;
int *j;
while (fgets(bufCoin, sizeof bufCoin, fileCoin) != NULL) {
j = addCoins(bufCoin);
int deno = j[0];
switch(deno){
case 5:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 10:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 20:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 50:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 100:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 200:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 500:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
case 1000:
Coins[i].denom = j[0];
Coins[i].count = j[1];
break;
default:
break;

}

i++;
}

下面是文件的定义

1000,3

500,4

200,20

100,30

50,5

20,3

10,40

5,20

其中第一个数字是以美分表示的面额,第二列是所述面额的数字。

这些是类型定义:

    /* The different denominations of coins available */
enum denomination
{
FIVE_CENTS, TEN_CENTS, TWENTY_CENTS, FIFTY_CENTS, ONE_DOLLAR,
TWO_DOLLARS, FIVE_DOLLARS, TEN_DOLLARS
};

/* Each coin in the coins array will have a denomination (20 cents,
* 50 cents, etc) and a count - how many of that coin do we have on hand
*/
struct coin
{
enum denomination denom;
unsigned count;
};

最佳答案

strtok() 的第二个参数/strtok_r()通过预期 0 来描述一组 分隔符-终止数组 char s,那是一个C-“字符串”。

来自 strtok() / strtok_r() 's man-page :

The delim argument specifies a set of bytes that delimit the tokens in the parsed string.

所以它的用法应该是:

const char deli[2] = {',', '\0'};
...
char * denomination = strtok_r(val, deli, &ptr);

或更直接:

const char deli[] = ",";
...
char * denomination = strtok_r(val, deli, &ptr);

或者只是删除 deli 的定义并做:

char * denomination = strtok_r(val, ";", &ptr);

代码还应检查是否调用了 strtok_t()返回 NULL在将结果传递给 atoi() 之前, 因为后者如果被喂食 NULL 将会惨败.

关于c - 段错误难题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26217537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com