一個使用strtok出錯的例子

來源:互聯網
上載者:User

chartempName1[50];char*tempName2 = NULL;chartempName3[5][50];memcpy(tempName3[0], "F:\\1001_1_1.bmp", sizeof(tempName3[0]));memcpy(tempName3[1], "F:\\1001_1_2.bmp", sizeof(tempName3[1]));memcpy(tempName3[2], "F:\\1001_1_3.bmp", sizeof(tempName3[2]));memcpy(tempName3[3], "F:\\1001_1_4.bmp", sizeof(tempName3[3]));memcpy(tempName3[4], "F:\\1001_1_5.bmp", sizeof(tempName3[4]));for (k=0; k<5; k++){strcpy(tempName1, tempName3[k]);printf("%s\n", tempName1);strcpy(tempName2, "ssss");  //出錯!!//對tempName1進行處理//…strtok(tempName1, "_");strtok(NULL, "_");tempName2 = strtok(NULL, "_");}

上述代碼進入第二次迴圈時,執行完strcpy(tempName2, "ssss")後tempName1被改變,導致後續無法對tempName1進行處理。

原因:

tempName2 = strtok(NULL, "_")後tempName2指向tempName1數組中第二個"_"後的元素地址。

因此第二次迴圈開始對tempName1賦完值後(strcpy(tempName1, tempName3[k])),再對tempName2(strcpy(tempName2, "ssss"))賦值是不對的,這樣會修改了tempName1的資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.