C question time

Having digested an introduction in C does not mean you are a seasoned C programmer!

hmmm is this the new nds?

Pointers are connected to real memory space. Pointers can be seen as globals. But pointers have the nasty behaviour of shutting of memory if you forget to free the memory space. Also the interplay between pointers and methods must be done carefully, not allocating memspace in a method and then returning a pointer to it. The free-ing process will get messy!

So possible trouble will be ahead! Working with malloc and free and pointers makes C programming really different from programming in JAVA or C#. You need another kind of thinking.

Here a the question: (hm it takes a bit of preparing, sorry)

Say we have a struct called LINE

This struct consists of two structs called POINT and three floats

struct POINT{

float x, y;

}

struct LINE

{

struct POINT* pointPTR1;

struct POINT*pointPTR2;

float cx, cy, cc;

}

What we need is two lines parallel to line someLine (someLinePTR) (bouncing a ball with width for instance needs this)

Normally (coming from JAVA or whatever) I would have this someLine declared and call a class method passing the variable to this someLine and returning an array consisting of two lines:

(returnArray *) giveMeTwoParallelLines( someLinePtr, distance){

struct LINE* myFirstParallelLinePTR = makeAParallelLine (someLinePtr, distance);//another method returns a pointer

struct LINE* mySecondParallelLinePTR = makeAParallelLine (someLinePtr, -distance);

//returning the results in an array

(struct LINE*) returnArray[] = {  myFirstParallelLinePTR , mySecondParallelLinePTR  };

return returnArray;

}

this method is called like this:

(struct LINE*) returnArray[] = giveMeTwoParallelLines( someLinePtr, 50);

elements from returnArray can be used further on.

What is wrong here? (Take the above as an indication how the task is done, details can be different)

This is the clue:

The compiler indicates (or the app crashes) memory leaks…

Having memory leaks means that memory is allocated but not freed. In Xcode (Objective C)you can run an app inside a memory leak analizer. Devcpp doesn’t offer this service!

The whole structure of making parallel lines must be solved differently. How?

Answer in some other blog!

This was a real stupidity I committed in XCODE objective C for the Iphone (a version of C that admits classes, but for the rest is like normal C.)

http://en.wikibooks.org/wiki/C_Programming/Memory_management

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: