计数未定义字符数组的索引的#用C

问题描述 投票:-1回答:2

我试图计数其被用作在函数中的参数的未定义字符数组的索引的数目。

我已经意识到,如果我的数组是固定的,我可以使用“的sizeof”,这是不是这里的情况。

尝试:

int counting(char *name3) {
  int count = 0;
  int i;

  //I have no idea what to put as my condition nor do I believe 
  //I am approaching this situation correctly...
  for (i = 0; i < sizeof(name3); i++) {
      if (name3[i] != '\0') {
        count++;
      }
  }
return count;
}

然后,如果它是由下面的代码运行

int main(void) {
char *name = "Lovely";
int x = counting(name);
printf ("The value of x = %d", x);

打印:x的值= 0

任何帮助或指针将是惊人的。先感谢您。

c arrays
2个回答
0
投票
#include <stdio.h>

int main()
{

    int i=0;
    char *name = "pritesh";
    for(i=0;;i++)
    {  
        if(name[i] == '\0')
        {
            break;
        }
    }
    printf("%d", i);

    return 0;
}

这应该工作

注意:这可能是语法不正确的,因为我没有,因为很长一段时间了我的手ç


1
投票

在C中,每个字符串以“\ 0”(空字符)结束 您可以重复,直到你遇到空字符

示例代码会是这样的

char* name = "Some Name";
int len = 0;
while (name[len] != '\0') {
    len++;
}

此外,如果它是一个字符指针,而不是字符数组,sizeof(char*)将始终在32位应用程序返回4和64位应用程序(“指示器”本身的大小 - 存储地址大小)返回8

© www.soinside.com 2019 - 2024. All rights reserved.