C: pointerArrayExample

Working with structs….:

Having a struct you need a pointer: (for passing by reference etc)

(this is a picture of a dutch pointer 🙂

SOMESTRUCT myExample;

SOMESTRUCT* myExamplePtr;

myExamplePtr = &myExample;

myExamplePtr->someElement = 78;

but this working with real variable and pointer becomes a bit cumbersome, why not only use the pointer?

SOMESTRUCT* myExamplePtr;

myExamplePtr->someElement = 78;

well then you app crashes! CRASH!

when you don’t bother to declare the real variable, you have to use malloc instead, making memory available:

SOMESTRUCT* myExamplePtr;
myExamplePtr= (SOMESTRUCT*) malloc( sizeof(SOMESTRUCT) );
if( myExamplePtr!= NULL ) {
  myExamplePtr->someElement = 254;
}
But dont forget to free this pointer:
free( myExamplePtr);

So these two ways of using pointers are equivalent, the normal declaration taking care of "garbage collection" the malloc way, is doing this yourself.

An example "DevCPP_mallocTest" using this malloc in a pointerarray is in the folder with the other examples:

http://cid-58814201e79976dd.skydrive.live.com/self.aspx/iepro/DevCPP%5E_mallocTest.zip

some basic  info about malloc:

http://www.elook.org/programming/c/malloc.html

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: