Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Setting up arrays in C - fixed size at compile time, or dynamic

You can store a whole series of data values of the same type in an array in C.

The easiest way to declare an array is something like:
  int history[20];
and that will give you an array of 20 elements - which you can refer to as elements number 0 to 19, so:
  history[4] = 1234;
to set the fifth element (care - counting starts at 0), or in a more general case"
  history[iposn] = 2345;
where iposn is an integer variable itself, somewhere in the range 0 to 19, or looping through the values 0 to 19.

You won't always know when you write your program how big you need your array to be, and a very basic but simple solution is sometimes simply to allow as many elements as the maximum will ever be, then a few more for safety. This is a very crude technique, wasteful of memory, and prone to problems when it turns out that the figure you chose was not enough. I remember an example I wrote a year or two back on a course where I chose to have 10 elements in an array, which was to hold the ages of all the brothers and sisters of someone .... then I went round the room asking "how many siblings have you" to each of my class. One lady replied "22", and in subsequent conversation that turned out to be the actual truth, though she sis admit that about a half of them were halfbrothers and halfsisters.

You can easily change the size of the array at the time you compile the program by using a defined constant to the preprocessor - so:
  #define TOP 6
and then:
  int history[TOP];
and indeed you can also can also make the setting of such a variable from the compile line if you wish:
  munchkin:cj grahamellis$ gcc -o afp -D TOP=3 afp.c
but you then need to amend your preprocessor directives to ensure that the setting within the code is merely a fallback:
  #ifndef TOP
  #define TOP 6
  #endif


However, you're still looking at changing the size at compile time - if you want a program that can be altered at runtime, based on user inputs, values read from files or other resources, or passed in at the command line, you'll want to set up the memory area using functions such as malloc, calloc or realloc.
  int *history = (int *)calloc(howmany, sizeof(int));
The variable "howmany" is an int, which - by the time calloc is called - needs to have been set up to the array size that's required. The memory is allocated on the "heap" so it has a different scope - it's not released at the end of the block in which it is declared, and that turns out to be both useful ad dangerous (if you've ever heard people talk about "memory leaks", they're talking about a long running program that does a lot of things like calloc, but never releases the memory again).

There is a complete example showing fixed size arrays [here], and one that uses calloc [here]. You'll note that - once the array has been set up - BOTH examples go on to access the data using both the [] and the * notation ... and that's because an array name is simply a pointer to the first element of the memory block that's allocated, be it at compile or run time, and be it on the stack (lost at the end of the block) or heap (retained until the program ends or you release it).

Bear in mind that - with all arrays - you as the programmer are responsible for ensuring that you don't use the array name to address off the end of the allocated memory. That means that you have to do a lot of checking, and that you'll need in your code to have some sort of way of knowing how big an array is. You may do that by passing a count around, or by having a specific value in the end of the array that indicates "end of data". That's how strings work - with a null character at the end. With double quoted strings, that's automatic ([example]) but at other times - such as when you're handling a string as an array oc characters - you MUST check - [example].
(written 2011-01-24, updated 2011-01-25)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
C212 - C and C based languages - Memory Management
  [1497] Training Season Starts again! - (2008-01-07)
  [1581] What is an lvalue? (Perl, C) - (2008-03-18)
  [1589] Dynamic Memory Allocation in C - calloc, realloc - (2008-03-22)
  [1670] Dynamic Memory Allocation in C - (2008-06-09)
  [1845] Passing a table from Lua into C - (2008-10-18)
  [2669] Efficient use of dynamic memory - C and realloc - (2010-03-10)
  [2848] C course - final course example puts it all together - (2010-07-02)
  [3118] Arrays of arrays - or 2D arrays. How to program tables. - (2011-01-02)
  [3386] Adding the pieces together to make a complete language - C - (2011-08-11)
  [3416] Storing Tcl source code encoded, and running via your own C program - (2011-09-02)
  [4128] Allocating memory dynamically in a static language like C - (2013-06-30)
  [4340] Simple C structs - building up to full, dynamic example - (2014-12-03)
  [4634] Regression testing - via a very short C testing framework - (2016-01-29)
  [4635] Encapsulating logic in functions and structs - the C approach to Object Oriented techniques - (2016-01-30)

C206 - C and C based languages - Character Strings
  [1338] Handling Binary data in Tcl (with a note on C) - (2007-09-09)
  [2843] String functions in C - (2010-06-30)
  [2844] Learning about Regular Expressions in C through examples - (2010-06-30)
  [3122] When is a program complete? - (2011-01-06)
  [3146] Strings in C - (2011-01-25)
  [3593] Chars, char arrays and strings in C. Some early cautions and pitfalls. - (2012-01-26)
  [3718] Splitting a record into individual data values in C - (2012-05-04)
  [4556] Strings in C - strncmp strncpy and friends - (2015-10-27)
  [4633] String handling in C - new examples of extracting integers from a string - (2016-01-27)

C205 - C and C based languages - Arrays
  [1614] When an array is not an array - (2008-04-17)
  [2002] New C Examples - pointers, realloc, structs and more - (2009-01-20)
  [2840] Just pass a pointer - do not duplicate the data - (2010-06-30)
  [3121] New year, new C Course - (2011-01-05)
  [3245] Collections in C and C++ - arrays, vectors and heap memory blocks - (2011-04-12)
  [4338] Passing arrays into functions in C - (2014-12-02)
  [4566] C - why is slow to write and debug) but fast to run? - (2015-11-01)


Back to
On time
Previous and next
or
Horse's mouth home
Forward to
Structures v Structure Pointers in C. How, which, why.
Some other Articles
OpenGL / C / C++ - an example to get you started
Hotel star ratings - towards a better system of review
Structures v Structure Pointers in C. How, which, why.
Setting up arrays in C - fixed size at compile time, or dynamic
On time
Private and Public - and things between
Wiltshire Rail services - a golden opportunity
Django - separating the HTML from the view / model
Steering our Python courses towards wxPython, SQLite and Django
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3144_.html • PAGE BUILT: Sun Oct 11 16:07:41 2020 • BUILD SYSTEM: JelliaJamb