我正在按照 cLearnthehardway 的练习 8 编写以下代码,我有 2 个问题
- 在打印和整数时,它使用 %ld 来打印它们而不是 %d !!
- 打印区域[10]时//超出范围,打印了0!为什么它没有向我显示错误,而 valgrind(6erros) 却显示错误
#include<stdio.h>
int main(int argc,char *argv[])
{
int areas[]={10,12,13,14,20};
char name[]="Zed";
char full_name[]={'Z','e','d',' ','A','.',' ','S','h','a','w','\0'};
printf("The size of an int: %ld\n", sizeof(int));//why didn't we use %d instead of %ld(*)
printf("The size of areas (int[]):%ld\n",sizeof(areas));//*
printf("The number of ints in areas : %ld\n",sizeof(areas)/sizeof(int));//*
printf("The first area is %d, the second area is %d\n",areas[0],areas[1]);//Printed areas[10]=0!!
printf("The size of a char is: %ld\n",sizeof(char));//*
printf("The size of name(char[]) is:%ld\n",sizeof(name));//*
printf("The number of chars is : %ld\n",sizeof(name)/sizeof(char));//*
printf("the size of FULL NAME (char[]) is:%ld\n",sizeof(full_name));//*
printf("The number of chars in full name is %ld\n",sizeof(full_name)/sizeof(char));//*
printf("name=\"%s\" and full name =\"%s\"\n",name,full_name);// what is \"%s\" \ is an ESCAPE
return 0;
}
最佳答案
运算符sizeof
返回size_t
类型的值。通常,size_t
被定义为unsigned long
(尽管它可以是任何无符号整数类型)。根据 C 标准,sizeof( long )
大于或等于 sizeof( int )
。例如,sizeof( long )
可以等于 8,而 sizeof( int )
可以等于 4。因此,在代码中您显示了格式说明符 %ld
用于输出 long int
类型的对象,但最好使用 %zu
,其中标志 z
表示对象将输出 size_t 类型。
对于数组,编译器不会检查数组的边界。程序员应该正确指定数组元素的索引。
关于c - c 中的大小和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27048265/