2014-11-20 87 views
-2

我在练习8下面的代码被写入以下cLearnthehardway,我有2个问题大小和数组在C

  • 同时打印和整数它用来%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; 
} 
+0

问题已经被答案解决,我选择了完美的一个:) – 2014-11-21 13:18:31

回答

1

运算符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将被输出。

至于数组,那么编译器不检查数组的边界。程序员应该正确指定数组元素的索引。

+0

完美答案谢谢:) – 2014-11-20 20:25:19

0

关于打印尺寸:sizeof(int)是整体式size_t的。在某些类型的机器上,与其他机器上的unsigned int相同,它与unsigned long相同。在实践中,尺寸是小的整数,因此你就可以

printf("The size of an int: %d\n", (int) sizeof(int)); 

迂腐你可以#include <inttypes.h>,并使用一些格式(例如%zu)那里。

关于超出范围的索引,它们在运行时会导致buffer overflow(其中可能是 SEGV)。这是undefined behavior的一个示例。总是避免它。这里有可能发生在UB上的恐怖的examples

+0

thx兄弟,理解:) – 2014-11-20 20:24:49

+0

被称为“兄弟”是奇怪的,你可能比我的大多数孩子更年轻(我有6大 - 儿童和4个孩子,其中3个成年人和工作...)。 – 2014-11-20 20:57:38

+0

是的你对,我的歉意先生:) – 2014-11-20 23:38:51