#include<stdio.h>
int main(){
char*s[]={"we will teach you how to","Move a mountain","Level a building","Erase the past","Make a million"};
printf("%u",sizeof(s));
return 0; }
运行此命令将输出20。大小不应该=每个数组中的元素数x数组数x sizeof(char)吗?sizeof(s + 1)也会打印4个字节。此外,如何获取指针数组的数目而没有。上面提到的代码中每个指针数组中没有硬编码的元素的数量?
您的数组s
中有5个条目。每个条目都是一个char *
。因此,sizeof(s)
是5*sizeof(char *)
。看来您正在32位系统上运行,所以指针的大小为4个字节。因此,总大小为20个字节。
我如何获得指针数组的数量而没有。每个指针数组中的元素数]
问题的这一部分还不清楚。只有一个“指针数组”,即s
。要获取数组中的元素数,可以执行以下操作:
sizeof(s) / sizeof(*s)
要获取数组索引为i
的字符串的长度,可以执行以下操作:
strlen(s[i])
我认为您混淆了如何使用带char的指针和带字符串的指针
#include<stdio.h>
#include<string.h>
int main()
{
char s[] = {'a','b','c','d','e'};
printf("%s",s);
int len=strlen(s);
printf("%d",len);
return 0;
}
o / pabcde5 //在这里您可以检查char数组中有多少个元素,并确定char数组中有多少个大小]
基于您系统的指针大小
现在来解决您的问题:
#include<stdio.h>
#include<string.h>
int main()
{
char s[] = {"a","b","c","d","e"}; //hear give an error: excess elements in char array initializer because you work with string in your programme
printf("%u",sizeof(s));
// int len=strlen(s);
// printf("%d",len);
return 0;
}
您可以检查数组元素的位置
#include<stdio.h>
int main()
{
char*s[]={"abc","xyz","def","zes"};
printf("%s",s[0]); //here required the pointer
return 0;
}
o / p abc
//这里最重要字符数组的大小:
#include<stdio.h>
int main()
{
char s[]={'a','b','c','d'};
printf("%d",sizeof(s));
return 0;
}
o / p 4
希望我的答案对您有所了解。