Main Content

New C Examples - pointers, realloc, structs and more

Archive - Originally posted on "The Horse's Mouth" - 2009-01-20 18:36:29 - Graham Ellis

Every time I program in C, I marvel at how clever the language is ... yet at the same time I curse some of the devices that are used to perform certain actions, which make the code that much more of a 'puzzle' to right.

I've finished a 2 day C Programming course today ... and written a whole raft of new examples as I did so; the elegates gain so much more from seeing HOW I achieve the results as well as just seeing the results themselves. So I give you:

• Loops and conditionals - throwing a die until you get a six, then printing out the sum / average of all the throws [source]

• A program to head in your height and weight (in once file) and call functions in another to calculate your BMI and also to return a comment about your health. [source] and [source]

• The significance of call by value v call by name. If you call a function and pass it a COPY of the data, then no matter how much it changes the copy, it won't effect the original. But if you pass in a POINTER so that the function works ont he same data, then it CAN change it. Which is best? Both have their uses - it's a case of horses for courses. Examples - [source] and [source].

• Summing numbers typed in on the command line [source]

• How to pass an array to a function in C [source]

• Passing pointers into functions in order to allow the function to return multiple values [source]

• The difference between the . and the -> operator when used to access a member of a structure or union in C [source]

• Reading data from a file, tokenising each line into a structure and storing those structures in an array [source]

• Examples of the #define and #include pre-processor directives for setting up compile time constants and including a file of headers within multiple source files. [source] and [source]

• How do you read a file of unknown length in C and store it in memory, when you have to give you arrays a fixed size? You use the realloc function. This example shows you how to do it, setting up a block of memory which is expanded to take however much data you have in the file [source]