如何在C中计算字符串数组元素?
我希望我的循环重复次数与“水果”数组中的字符串重复次数相同 首先尝试使用“while”循环,但我无法使它正常工作(现在它被注释了),因为(如调试器所示)它在第4次迭代时出错。此方法应适用于字符或整数数组,但不适用于字符串数组。为什么是这样 然后我尝试使用“for”循环,并希望它在达到数组中存储在“count”变量中的字符串元素总数时停止。然而,我找不到一个好的方法来计算数组中字符串的数量。这可能吗?“sizeof”操作符在这里似乎不是一个好的解决方案 提前感谢您的回复如何在C中计算字符串数组元素?,c,arrays,string,for-loop,while-loop,C,Arrays,String,For Loop,While Loop,我希望我的循环重复次数与“水果”数组中的字符串重复次数相同 首先尝试使用“while”循环,但我无法使它正常工作(现在它被注释了),因为(如调试器所示)它在第4次迭代时出错。此方法应适用于字符或整数数组,但不适用于字符串数组。为什么是这样 然后我尝试使用“for”循环,并希望它在达到数组中存储在“count”变量中的字符串元素总数时停止。然而,我找不到一个好的方法来计算数组中字符串的数量。这可能吗?“sizeof”操作符在这里似乎不是一个好的解决方案 提前感谢您的回复 #include <
#include <stdio.h>
int main()
{
char *fruits[]={"Apple", "Grapefruit", "Banana"};
int i=0;
int count=sizeof(*fruits);
char **bitter=&fruits[1];
printf("Bitter fruit is: %s", *bitter);
puts(" ");
printf("All fruits are: ");
for (;i<count;i++);
{
printf("%s ",*(fruits+i));
}
/*
while ( fruits[i] != '\0')
{
printf("%s ",*(fruits+i));
}
stuff above failed. why?
*/
return 0;
}
#包括
int main()
{
char*水果[]={“苹果”、“葡萄柚”、“香蕉”};
int i=0;
整数计数=sizeof(*水果);
炭**苦=&水果[1];
printf(“苦果为:%s”,*苦果);
认沽权(“”);
printf(“所有水果都是:”);
对于(;i来说,一个简单的方法是在列表中添加一个空值:
char *fruits[] = {"Apple", "Grapefruit", "Banana", NULL};
然后您可以像这样打印所有水果:
int i = 0;
while (fruits[i] != NULL) {
printf ("%s ",*(fruits+i));
i++;
}
关于原始while循环失败的原因:
- 您的
i
不会递增
- 您正在检查
fruits[i]!='\0'
其中fruits[i]
是指向char
的指针,而'\0'
是一个char
等于0。因此,您基本上是在检查fruits[i]
是否指向0,但对于前三个迭代来说,这不是fruits[i]的情况
指向相应结果的第一个字符,在第四次迭代中,结果[i]
指向不属于程序的内存位置
您也可以考虑从标题字符串中使用String()。h:
#include <stdio.h>
#include <string.h>
int main()
{
char *myarray[] = {"Mere", "Pere", "Gutui"};
int i = 0;
int lungime = strlen(*myarray);
while (i < (lungime - 1)){
printf("Fruit no. %d is %s\n", i, *(myarray + i));
i++;
}
return 0;
}
#包括
#包括
int main()
{
char*myarray[]={“仅仅”、“佩雷”、“古图”};
int i=0;
int lungime=strlen(*myarray);
而(i<(lungime-1)){
printf(“水果编号%d是%s\n”,i,*(myarray+i));
i++;
}
返回0;
}
#包括
int main()
{
char*水果[]={“苹果”、“葡萄柚”、“香蕉”};
int i=0;
int count=sizeof(水果)/sizeof(水果[0]);
炭**苦=&水果[1];
printf(“苦果为:%s\n”,*苦果);
printf(“所有水果均为:\n”);
对于(i=0;i好,但是写fruits[i]
可能比写*(fruits+i)
更干净。谢谢@睫毛。@PaulR*(fruits+i)
是不是因为我最近试图熟悉指针。使用进行循环和计算数组字符串元素的方法可能吗?-1这是完全错误的。您使用的字符串长度“仅仅”
作为myarray
的长度,strlen
不返回数组的长度。它返回以nul结尾的字符串的长度。这不起作用,因为(sizeof(fruits[0])小于sizeof(fruits[1]),所以没有统一的大小。您的方法可以使用固定大小的元素数组,例如int number[]等
#include <stdio.h>
int main()
{
char *fruits[]={"Apple", "Grapefruit", "Banana"};
int i=0;
int count=sizeof(fruits)/sizeof(fruits[0]);
char **bitter=&fruits[1];
printf("Bitter fruit is: %s\n", *bitter);
printf("All fruits are:\n");
for(i=0;i<count;i++)
{
printf("%s\n",fruits[i]);
}
return 0;
}