gpt4 book ai didi

c - 二维数组 - 每行都被下一行覆盖

转载 作者:行者123 更新时间:2023-11-30 17:10:46 25 4
gpt4 key购买 nike

我正在从文件中读入。每当我读到“transition”这个词时,我都会尝试添加接下来出现的 5 个元素到二维数组中。我有一堆 printf,我已经注释掉了它们,表明我正在添加正确的元素。但是,一旦我完成从文件中的读入,我就会循环检查我的二维数组值,它们都已被最后一行的值覆盖。

这是我的代码

State* allStates[1002];
State* currentState;
char* input = argv[1];
char* inputStr = argv[2];
int maxTrans = atoi(argv[3]);
int transCount = -1;
FILE* inputFile;
char* transition[maxTrans][5];

inputFile = fopen(input, "r");
if (inputFile == 0)
{
perror("Can't open file\n");
exit(-1);
}
else
{
char next[1000];
//int counter = 0;
while (fgets(next, 1000, inputFile) != NULL)
{
char *nextWord;
nextWord = strtok_r(next, "\t");

if (strcmp(nextWord, "state") == 0)
{

//counter++;
nextWord = strtok_r(NULL, "\t");
//puts(nextWord);
int q = atoi(nextWord);
nextWord = strtok_r(NULL, "\n");
//puts(nextWord);
if (strcmp(nextWord, "accept") == 0)
{
State* newState = makeState(q, 1, 0, 0);
allStates[q] = newState;
}
else if (strcmp(nextWord, "reject") == 0)
{
State* newState = makeState(q, 0, 1, 0);
allStates[q] = newState;
}
else if (strcmp(nextWord, "start") == 0)
{
State* newState = makeState(q, 0, 0, 1);
allStates[q] = newState;
currentState = newState;
}
else
{
State* newState = makeState(q, 0, 0, 0);
allStates[q] = newState;
}
}
if (strcmp(nextWord, "transition") == 0)
{
//printf("\n");
//setup 2d array of transitions
transCount++;
nextWord = strtok_r(NULL, "\t");
//puts(nextWord);
transition[transCount][0] = nextWord;
//printf("%c", *transition[transCount][0]);
nextWord = strtok_r(NULL, "\t");
//puts(nextWord);
transition[transCount][1] = nextWord;
//printf("%c", *transition[transCount][1]);
nextWord = strtok_r(NULL, "\t");
//puts(nextWord);
transition[transCount][2] = nextWord;
//printf("%c", *transition[transCount][2]);
nextWord = strtok_r(NULL, "\t");
//puts(nextWord);
transition[transCount][3] = nextWord;
//printf("%c", *transition[transCount][3]);
nextWord = strtok_r(NULL, "\n");
//puts(nextWord);
transition[transCount][4] = nextWord;
//printf("%c", *transition[transCount][4]);

}
}

}
fclose(inputFile);

int u = 0;
int y = 0;
char m = 'm';
for (u; u < 12; u++)
{
printf("\n");
for (y = 0; y < 5; y++)
{
//transition[u][y] = &m;

printf("%c", *transition[u][y]);


}
}

如果我正在读取的文件如下所示,

过渡 0 x 0 x R

过渡 0 1 4 1 L

过渡 0 0 1 x R

我希望数组看起来像这样

0x0xR

0141L

001xR

数组的值将是

001xR

001xR

001xR

我知道覆盖发生在每一行。即:当我写入第 2 行时,值变为:

0141L

0141L

我真的不知道如何解决它。

最佳答案

问题在于我错误地使用了 strtok()。我采纳了 Dmitri 的建议并使用 strdup() 为新字符串分配内存,并且我得到了正确的结果。

nextWord = strtok(NULL, "\t");
temp = strdup(nextWord);
transition[transCount][0] = temp;

关于c - 二维数组 - 每行都被下一行覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747883/

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