【问题标题】:How to find length of particular string in array of pointer to string?如何在指向字符串的指针数组中查找特定字符串的长度?
【发布时间】:2022-01-04 23:28:23
【问题描述】:

如何从指向字符串的指针数组中找到字符串的长度。例如,如果我想找到字符串“apple”的长度,那么我该如何计算它的长度。我尝试了很多方法,但我做不到,如果我做 sizeof(str[0]) 它返回指针的大小(我的 32 位设备中的 4 个字节),我想知道它们是否存储在彼此相邻的内存位置还是不行?

const char *str[] = {
        "apple", "ball", "cat", "dog", "mep", "helsdf"
    };

【问题讨论】:

  • 它们可能彼此相邻,也可能不相邻。它们可以按任何顺序排列,字符串之间可以有任意数量的字节。编写 C 时,代码的设计应使您无需知道也不关心字符串文字的存储位置。
  • 听起来您在问不同且不相关的问题。每个字符串的长度是明确定义的,但它不会告诉您它们在内存中是否相邻。另外,为什么你想知道它们在内存中是否相邻? (无所事事的好奇心是一个完全正当的理由;我想不出另一个理由。)

标签: arrays c string pointers string-length


【解决方案1】:

...我想知道它们是否存储在彼此相邻的内存位置?

检查您是否需要查看指针值并进行一些指针运算。

喜欢:

// 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

请记住,每次编译源代码时,上述代码的结果可能会发生变化。

【讨论】:

    【解决方案2】:

    使用 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;
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-28
      • 2014-11-29
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多