簡體   English   中英

當我們可以在函數內部使用strlen()獲取單詞的長度時,為什么將字符串的長度作為參數發送給函數?

[英]Why do we send the lengths of strings as parameters to functions when we can use strlen() inside the function to get the lengths of the words?

我思考這個問題已有一段時間了,今天我遇到了一個教程,決定問一下。

互聯網上的許多教程都使用main函數內部的strlen()獲取字符串的長度,並將其作為參數發送給函數。 為什么我們不簡單地將字符串傳遞給函數並在函數內部使用strlen()?

例:

人們為什么使用此:

int function (const char * word1, int len1, const char * word2, int len2){
    ...
}

int main (){
    distance (word1, strlen(word1), word2, strlen(word2));
}

代替這個:

int function (char * word1, char * word2){
    ...
    int len1 = strlen(word1);
    int len2 = strlen(word2);
    ...
}

int main (){
    distance (word1, word2);
}

通過長度

  1. 節省CPU時間( strlenO(n)函數-測量字符串需要時間)
  2. 允許您傳遞子字符串或處理非空終止的字符數組。

一些函數采用您的方法並自行測量輸入字符串的長度。 在運行時效率和較小的API便利性之間進行權衡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM