C中未定义的char数组的索引计数#



我正在尝试计算函数中用作参数的未定义char数组的索引数。

我已经知道,如果我的数组是固定的,我可以使用"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] != '') {
count++;
}
}
return count;
}

然后,如果它由以下代码运行

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

打印:x=0 的值

任何帮助或指示都将是惊人的。提前谢谢。

在C中,每个字符串都以"\0"(Null字符)结尾
您可以迭代,直到满足Null字符

示例代码如下

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

此外,如果它是一个char指针,而不是char数组,sizeof(char*)在32位应用程序中总是返回4,在64位应用程序中将返回8("指针"本身的大小-内存地址大小)

#include <stdio.h>
int main()
{
int i=0;
char *name = "pritesh";
for(i=0;;i++)
{  
if(name[i] == '')
{
break;
}
}
printf("%d", i);
return 0;
}

这应该工作

注意:这可能在语法上不正确,因为我已经很久没有接触过c了

最新更新