2014-03-29 69 views
-2

我正在C中創建程序,它爲數組分配動態內存,並且我製作了顯示這些數字的函數,但遺憾的是我不知道如何在未分配內存時添加異常並寫入「Can' t顯示任何內容,因爲內存未被分配「。這是我的代碼。C動態數組

void printing(int *data, int size){ 
    if (data != NULL){ 
     for (int i = 0; i < size; ++i){ 
      printf("%d\n", data[i]); 
     } 
    } else { 
     printf("Nothing to show\n"); 
    } 
} 
+0

http://www.codingunit.com/c-tutorial-the-functions-malloc-and-free – OldProgrammer

+0

C不具有內置的異常處理。不過,您可以使用第三方庫。去谷歌上查詢! – dtech

+0

你是什麼意思的「添加例外」?你顯示的代碼檢查一個空指針,這是有道理的。也許它應該檢查'大小'是否合理。但目前還不清楚你想做什麼。從外觀上看,內存正在被分配到你所顯示的這個功能之外。動態內存分配函數,如'malloc',在發生分配失敗時返回NULL。 – lurker

回答

1
int * data = malloc(count * sizeof(int)); 
if (data) printf("Allocation succeeded"); 
else printf("Allocation failed");