如何從指向字串的指標陣列中找到字串的長度。例如,如果我想找到字串“apple”的長度,那么我該如何計算它的長度。我嘗試了很多方法,但我不能,如果我做 sizeof(str[0]) 它回傳指標的大小(我的 32 位設備中的 4 個位元組),我想知道它們是否存盤在彼此相鄰的記憶體位置或不?
const char *str[] = {
"apple", "ball", "cat", "dog", "mep", "helsdf"
};
uj5u.com熱心網友回復:
使用 string.h 中的 strlen()
#include <stdio.h>
#include <string.h>
int main() {
const char *str[] = {
"apple", "ball", "cat", "dog", "mep", "helsdf"
};
printf("Length of \"%s\": %zu\n", str[0], strlen(str[0]));
return 0;
}
uj5u.com熱心網友回復:
...我想知道它們是否存盤在彼此相鄰的記憶體位置中?
要檢查您是否需要查看指標值并進行一些指標運算。
喜歡:
// Print the location of each substring
for (size_t i = 0; i < (sizeof str / sizeof str[0]); i)
{
printf("%p : %s\n", (void*)str[i], str[i]);
}
// Check if str[i 1] is located just after str[i]
for (size_t i = 0; i < (sizeof str / sizeof str[0] - 1); i)
{
if ( (str[i] strlen(str[i]) 1) == str[i 1] )
{
printf("%s is stored just after %s\n", str[i 1], str[i]);
}
}
可能的輸出:
0x558cfd6e5004 : apple
0x558cfd6e500a : ball
0x558cfd6e500f : cat
0x558cfd6e5013 : dog
0x558cfd6e5017 : mep
0x558cfd6e501b : helsdf
ball is stored just after apple
cat is stored just after ball
dog is stored just after cat
mep is stored just after dog
helsdf is stored just after mep
請記住,每次編譯源代碼時,上述代碼的結果可能會發生變化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/375259.html
