每次运行此代码时,我都会得到3.但它应该是10.如何修复它? [英] Every time I run this code, I get 3. But it should be 10. How to fix it?
本文介绍了每次运行此代码时,我都会得到3.但它应该是10.如何修复它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
char* element[] = "Hydrogen" ,"Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon" };
n=strlen(element);
printf("%d",n);
return 0;
}
我的尝试:
What I have tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
char* element[] = {"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon"};
n=strlen(element);
printf("%d",n);
return 0;
}
推荐答案
如果你看一下strlen的定义: strlen - C ++参考a> [ ^ ]它接受一个参数,它是一个指向char的指针 - 换句话说就是一个字符串 - 并返回第一个空值的字符数。
这不是传递它的内容:element
是一个指向char的指针数组 - 或一个字符串数组。因此,它将数组看作是一个字符串,并且让它非常错误。
将它传递给数组的一个元素,它将返回你想要什么!
If you look at the definition of strlen: strlen - C++ Reference[^] it takes a parameter which is a pointer to a char - or a string in other words - and returns the number of characters up to the first null value.
That isn't what to are passing it:element
is an array of pointers to char -or an array of strings. So it looks at the array as if it was a string, and gets it horribly wrong.
Pass it one of the elements of the array, and it'll return what you want!
n=strlen(element[0]);
或
n=strlen(element[1]);
...
在编译时已知数组的大小。通常使用如下的宏
The size of an array is known at compile time. Usually a macro like the following is used
#define NELEM(a) (sizeof(a) / sizeof(a[0]))
尝试,例如
Try, for instance
#include <stdio.h>
#define NELEM(a) (sizeof(a) / sizeof(a[0]))
int main()
{
int n;
char* element[] = { "Hydrogen" ,"Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon" };
n = NELEM(element);
printf("%d\n",n);
return 0;
}
我们不能使用strlen来获取数组中元素的数量。
我已经为你解决了,并链接如下。
数组的长度字符串 [ ^ ]
We can not use strlen to get the count of elements in an array.
I have solved for you and linked as below.
length of an array of strings[^]
这篇关于每次运行此代码时,我都会得到3.但它应该是10.如何修复它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文