2014-11-20 88 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