gpt4 book ai didi

c - 循环似乎在到达 C 中的空字符之前终止

转载 作者:行者123 更新时间:2023-11-30 16:49:54 25 4
gpt4 key购买 nike

下面是我构建的 Tokenizer 的一部分。用户键入他们希望标记的字符串,该字符串将存储到 char 数组中,并且一旦字符串结束,就会放置一个空字符 ('\0')。经过几次测试后,这部分代码似乎工作正常。

当我创建数组 (newToken) 的数组 (tokenArray) 时,我遇到的问题稍后会在代码中出现。我使用函数来获取 token 数量和 token 长度。

我输入了字符串“测试铅笔计算器”。然后我将每个标记存储到一个数组中。问题是当我去打印数组的内容时,我打印的循环提前停止了。

这是一个示例输入/输出。我的评论(不在代码中)由

注明
$testing pencil calculator //string entered

complete index: 0 //index of the entire array, not the tokenized array
token length: 7 //length of 1st token "testing"
pointer: 0xbf953860
tokenIndex: 0 //index of the token array (array of arrays)
while loop iterations: 4 //number of times the while loop where i print is iterated. should be 7
test //the results of printing the first token

complete index: 8
token length: 6 //next token is "pencil"
tokenIndex: 1
while loop iterations: 5 //should be 6
penci //stops printing at penci

complete index: 15
token length: 10 //final token is "calculator"
pointer: 0xbf953862
tokenIndex: 2
while loop iterations: 5 //should be 10
calcu //stops printing at calcu

对于我来说,我根本无法弄清楚为什么 while 循环会在它应该退出之前退出。我怀疑这是我的方法的唯一问题,但在我弄清楚这一点之前,我无法解决其他错误。

下面是我的代码的一部分,负责此操作:

来自主:

  completeString[inputsize] = '\0';   

char tokenArray[numTokens+1];
tokenArray[numTokens] = '\0';
putTokensInArray(tokenArray, completeString);

我遇到错误的方法:

char ** putTokensInArray(char tokenArray[], char * completeString){
int completeIndex = 0;
int tokenIndex = 0;

while(tokenArray[tokenIndex] != '\0'){
int tokenLength = tokenSize(completeString, completeIndex);
char newToken [tokenLength+1];
newToken[tokenLength] = '\0';
tokenArray[tokenIndex] = *newToken;

printf("\ncomplete index: %d", completeIndex);
printf("\ntoken length: %d", tokenLength);
printf("\ntokenIndex: %d\n", tokenIndex);

int i = 0;
while(newToken[i] != '\0'){
newToken[i] = completeString[i + completeIndex];
i++;
}
completeIndex += (tokenLength+1);

printf("while loop iterations: %d\n", i);

for(int j = 0; newToken[j] != '\0'; j++){
printf("%c", newToken[j]);
}

tokenIndex++;
tokenLength = 0;

}//big while loop
}//putTokensInArray Method

我尝试了几种方法,但就是无法掌握它。我是 C 新手,所以完全有可能我犯了指针错误或访问了不应该的内存;关于这一点,我将如何实现 malloc() 和 free() ?我一直在阅读并似乎可以工作,但我无法实现这些功能。

最佳答案

您正在将未初始化的字符数组传递给您的函数 putTokensInArray 。稍后在该函数中,在 while 中您正在检查的循环条件 \0对于从 0 开始的每个元素。但是,由于数组未初始化,这些字符可以是任何字符。可能有一个\0之前numTokens+1第一个元素。

要解决此问题,请传递字符数组的长度,即 numTokensputTokensInArray作为附加参数。然后在 while 循环中执行以下条件检查:

while(tokenIndex < numTokens){

关于c - 循环似乎在到达 C 中的空字符之前终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42406592/

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