I’ve been programming in java for over a year now but am slowly teaching myself C / objectiveC whilst studying at uni from the book: Cocoa and Objective C – Up and Running. I’m still going through the introductory chapters familiarising myself with syntactical differences in C with java and have come across a section on dynamic memory, specifically on pointers. The example it provides is this:
#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 );
I understand the code – create an integer pointer, allocate 10 blocks of memory for it, create a second pointer to point at the first dynamic memory block of numbers, set the first block to 100, increment to the 2nd block and set that to 200, then use free() to free memory.
However, when I try to compile I get a series of errors. The code is saved in a c class called Dynamic.c in a folder called dynamic.
here is a print of what occurs in terminal:
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
If someone could explain why these errors occur I would be much obliged, I don’t see why they should be as its an example from a book.
Thanks.
Wrap it in a
main()function: