[問題] 新手試解leetcode的問題

看板C_and_CPP (C/C++)作者 (QQ)時間6年前 (2019/08/29 11:03), 6年前編輯推噓3(307)
留言10則, 4人參與, 6年前最新討論串1/1
最近邊看C的書想說邊試著一些簡單的leetcode 1108. Defanging an IP Address https://leetcode.com/problems/defanging-an-ip-address/ 錯誤截圖 https://imgur.com/lC1ovhg
在解的時候雖然有想法了 但是編譯不過 不太確定語法哪裡有問題所以想請大家指點一下 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) char Defang_Result[22]; char * defangIPaddr(char * address){ int count_1=0, count_2=0; for(count_1=0;count_1<22;count_1++){ if(*(address+count_1)!='.'){ Defang_Result[count_2]=*(address+count_1); count_2++; } else{ Defang_Result[count_2]='['; count_2++; Defang_Result[count_2]='.'; count_2++; Defang_Result[count_2]=']'; count_2++; } } return (Defang_Result); } 補充說明(Supplement): Leetcode 1108. Defanging an IP Address C language 感謝熱心的cutekid教學 在把該行修改後已可跑出結果 for(count_1=0;count_1<strlen(adress);count_1++){ 原因應為對adress超出範圍的讀取造成access violation -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.199.12 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1567047807.A.2CE.html

08/29 11:32, 6年前 , 1F
先猜Defang_Result[22]沒初始化讀到怪東西
08/29 11:32, 1F

08/29 11:39, 6年前 , 2F
第一組測試值是1.1.1.1 我有試宣告長度14剛好答案長度
08/29 11:39, 2F

08/29 11:39, 6年前 , 3F
但還是有問題
08/29 11:39, 3F

08/29 12:27, 6年前 , 4F
runtime error不是編譯錯誤 是執行過程錯誤 可能是陣列超
08/29 12:27, 4F

08/29 12:27, 6年前 , 5F
出範圍造成的
08/29 12:27, 5F

08/29 12:34, 6年前 , 6F
count1應該跑到字串結尾就要結束了 不然再跑下去count2可
08/29 12:34, 6F

08/29 12:34, 6年前 , 7F
能就超出範圍了
08/29 12:34, 7F

08/29 12:37, 6年前 , 8F
謝謝你 我會先查一下access violation相關的東西
08/29 12:37, 8F

08/29 12:38, 6年前 , 9F
以後這類長度未知的變數也會多注意
08/29 12:38, 9F
※ 編輯: mouwat (223.137.199.12 臺灣), 08/29/2019 12:47:12

09/01 01:00, 6年前 , 10F
不用查 就單純OOB access 注意不要犯就好
09/01 01:00, 10F
文章代碼(AID): #1TPq1_BE (C_and_CPP)
文章代碼(AID): #1TPq1_BE (C_and_CPP)