指針我一直在Java編程了一年多,但現在正在慢慢自學C /的ObjectiveC,同時在大學從書中學習:可可和目標C - 啓動和運行。我仍然閱讀介紹性章節,熟悉C語言與java的語法差異,並且已經遇到了關於動態內存的一節,特別是指針。它提供的示例是這樣的:與編圖掙扎:用C
#include <stdio.h>
#include <stdlib.h>
int* numbers;
numbers = malloc (sizeof(int) * 10);
//create a second variable to always point at the
//beginning of numbers memory block
int* numbersStart;
numbersStart = numbers;
*numbers = 100;
numbers++;
*numbers = 200;
//use the 'numbersStart' variable to free the memory instead
free(numbersStart);
我理解代碼 - 創建的整數指針,分配的存儲器10塊,創建一個第二指針在數字的第一動態存儲器塊指向,設置第一塊到100,遞增到第二個塊並將其設置爲200,然後使用free()釋放內存。
然而,當我嘗試編譯我收到了一系列的錯誤。代碼保存在一個名爲dynamic.c的文件夾中,名爲Dynamic.c。
這裏是在終端發生什麼打印:
gcc Dynamic.c -o Dynamic
Dynamic.c:13: warning: data definition has no type or storage class
Dynamic.c:13: error: conflicting types for ‘numbers’
Dynamic.c:12: error: previous declaration of ‘numbers’ was here
Dynamic.c:13: warning: initialization makes integer from pointer without a cast
Dynamic.c:13: error: initializer element is not constant
Dynamic.c:15: warning: data definition has no type or storage class
Dynamic.c:15: error: conflicting types for ‘numbersStart’
Dynamic.c:14: error: previous declaration of ‘numbersStart’ was here
Dynamic.c:15: error: initializer element is not constant
Dynamic.c:16: warning: data definition has no type or storage class
Dynamic.c:16: warning: initialization makes pointer from integer without a cast
Dynamic.c:17: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘++’ token
Dynamic.c:18: warning: data definition has no type or storage class
Dynamic.c:18: error: redefinition of ‘numbers’
Dynamic.c:16: error: previous definition of ‘numbers’ was here
Dynamic.c:18: warning: initialization makes pointer from integer without a cast
Dynamic.c:19: warning: data definition has no type or storage class
Dynamic.c:19: warning: parameter names (without types) in function declaration
Dynamic.c:19: error: conflicting types for ‘free’
/usr/include/stdlib.h:160: error: previous declaration of ‘free’ was here
如果有人能解釋爲什麼會發生這些錯誤,我將非常感激,我不明白爲什麼他們應該爲它從一個例子書。
謝謝。
我想你錯過了'的main()'方法。 – Mysticial 2012-03-05 19:40:16
你說_代碼保存在c class_中。那麼,什麼是C類?請顯示整個Dynamic.c – sidyll 2012-03-05 19:43:05