使用指针遍历char数组

chr*_*rry 6 c arrays string pointers sizeof

我是C语言的新手,想知道如何使用指针获取数组的每个元素。当且仅当您知道数组的大小时,这才容易。因此,让代码为:

#include <stdio.h>

int main (int argc, string argv[]) {
    char * text = "John Does Nothing";
    char text2[] = "John Does Nothing";

    int s_text = sizeof(text); // returns size of pointer. 8 in 64-bit machine
    int s_text2 = sizeof(text2); //returns 18. the seeked size.

    printf("first string: %s, size: %d\n second string: %s, size: %d\n", text, s_text, text2, s_text2);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在我要确定的大小text。为此,我发现字符串将以'\0'字符结尾。所以我写了以下函数:

int main (int argc, string argv[]) {
    char * text = "John Does Nothing";
    char text2[] = "John Does Nothing";

    int s_text = sizeof(text); // returns size of pointer. 8 in 64-bit machine
    int s_text2 = sizeof(text2); //returns 18. the seeked size.

    printf("first string: %s, size: %d\n second string: %s, size: %d\n", text, s_text, text2, s_text2);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,此功能不起作用,因为循环似乎没有终止。

那么,有没有办法获取char指针指向的s的实际大小?

mda*_*sev 7

不必检查指针,而必须检查当前值。您可以这样做:

int getSize (char * s) {
    char * t; // first copy the pointer to not change the original
    int size = 0;

    for (t = s; *t != '\0'; t++) {
        size++;
    }

    return size;
}
Run Code Online (Sandbox Code Playgroud)

或更简而言之:

int getSize (char * s) {
    char * t;    
    for (t = s; *t != '\0'; t++)
        ;
    return t - s;
}
Run Code Online (Sandbox Code Playgroud)