我最近開始研究 VS Ccode,我想在strtok()我的專案中使用該函式,但它無法正常編譯運行。我嘗試在在線編譯器中編譯此函式并且它有效,顯然問題出在 VScode 上。
有沒有人遇到過這個問題?有沒有人能解決我的問題?
#include <stdio.h>
#include <string.h>
char *base(char *line){
char *base, *dividedline;
const char s[3] = " ";
//get the first token
dividedline = strtok(line,s);
printf("%s\n", dividedline);
//get the others
for(int i; i!=3;i ){
dividedline = strtok(NULL,s);
printf("%s\n", dividedline);
if(i == 2){
base = dividedline;
}
return dividedline;
}
printf("finished");
return base;
}
int main()
{
printf("hello world \n");
char *l;
char str[80] = "hi test test";
l = base(str);
return 0;
}
當我用 VScode 編譯它時,該函式陷入無限回圈。我知道問題出在“dividedline = strtok(NULL,s);”這一行 尤其是 NULL,但我不知道出了什么問題。
uj5u.com熱心網友回復:
你的問題是:
for(int i; i!=3;i )
你不知道的初始值i是多少。你應該寫:
for (int i = 0; i != 3; i )
一種更具防御性的編程風格將使用:
for (int i = 0; i < 3; i )
如果初始化為負數,您的回圈仍可能需要很長時間,但如果初始化為正數且大于 3,則回圈會i立即停止。習慣用法在 C 中很常見。i<
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534148.html
上一篇:計算機等級考試二級C語言程式設計專項訓練題——程式修改題(一)
下一篇:這在C中使用不安全嗎?
