C 使用指针遍历 char 数组

标签 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;
}

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

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

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

    return size;
}

但是这个函数不起作用,因为循环似乎没有终止。

那么,有没有办法得到 char 的实际大小?指针指向了吗?

最佳答案

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

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

或者更简洁:

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

关于C 使用指针遍历 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48367022/

相关文章:

java - 由大元素和小元素组成的 float 组的总和

javascript - 如何使用 Javascript/JQuery/JSON 获取字符串的子集?

JavaScript:仅当单词包含整数 0-9 时,如何从字符串中删除最后一个单词?

c - 使用 GDB 进行 MPI 调试 - 当前上下文中没有符号 "i"

c++ - doxygen 一次注释多个变量

c - 多客户端聊天程序: send messages to all Clients

javascript - 使用 .map() 向数组中存在的对象添加新属性

c++ - 在 C/C++ 中存储 va_list 供以后使用的最佳方法

c - 检测断开连接的客户端而不阻塞 (C)

string - 有没有办法在 hadoop 中为字符串添加定界符?