【问题标题】:C iterate through char array with a pointerC用指针遍历char数组
【发布时间】:2018-06-30 05:23:40
【问题描述】:

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

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

那么,有没有办法获得指针指向的chars 的实际大小?

【问题讨论】:

  • 不幸的是,这并没有改变结果中的任何内容。不管我使用s != '\0'*s != '\0't != '\0'*t != '\0',它最终仍然没有终止......
  • 你正在重新实现strlen
  • 你的函数没有使用s,那么保留“原始”值有什么意义呢?

标签: c arrays string pointers sizeof


【解决方案1】:

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

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

【讨论】:

  • 唯一的问题是,它总是少返回一个字符。所以最后添加+1是可行的。仅当字符串开头不为空时。不过谢谢!我现在解决它:D
  • 另外,如果您使用的是空循环,请使用空大括号使其更容易检测,例如for (t = s; *t; t++) {}(您至少将 ';' 移到了自己的一行——这很好)
【解决方案2】:

这个for循环有错别字

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

我想你是说

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

尽管如此,通常该函数不提供与运算符sizeof 返回的值等效的值,即使您还要计算终止零。相反,它提供了一个与标准函数strlen 返回的值等效的值。

例如比较这段代码sn-p的输出

#include <string.h>
#include <stdio.h>

//...

char s[100] = "Hello christopher westburry";

printf( "sizeof( s ) = %zu\n", sizeof( s ) );
printf( "strlen( s ) = %zu\n", strlen( s ) + 1 );

所以你的函数只是计算字符串的长度。

用下面的方式定义它会更正确(使用指针)

size_t getSize ( const char * s ) 
{
    size_t size = 0;

    while ( *s++ ) ++size;

    return size;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 2012-11-06
    • 1970-01-01
    • 2017-03-19
    • 2020-08-19
    • 2021-01-26
    • 2021-05-29
    • 2016-11-12
    相关资源
    最近更新 更多