Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The best thing about C is that it's small and simple. The worst thing about C is that it's small and simple.</p> <p>There is no "built in" way to do what you want.</p> <p>Sure you can define linked lists of integers, but you'll have to deal with freeing the list after it's no longer needed, which can be harder than it sounds. And such a list will have a 100% overhead for pointer space. Not a problem for most applications, but something to think about.</p> <p>A better option is to use your own vector-like container that resizes itself as needed, "simulating" a C++ vector. <a href="https://stackoverflow.com/questions/3536153/c-dynamically-growing-array">This is the basic idea.</a> NB: This code omits error handling.</p> <p>Or as another recommendation said, implement a count in one pass, allocate exactly the counted numbewr of integers, then accumulate results in a second pass. Very stingy of memory, but obviously a run time penalty. Again not a big deal for small lists.</p> <p>Or you could adopt <a href="http://www.cs.virginia.edu/~lcc-win32/ccl/ccl.html" rel="nofollow noreferrer">this nice effort to build a container library for C</a>. </p> <p>Finally, you can sidestep returning a list entirely by providing instead a mapping primitive that accepts a callback function:</p> <pre><code>typedef int (*CHANNEL_DB_MAPPED_FUNCTION)(CHANNEL_DB *db, void *env); int map_onto_channel_db(CHANNEL_DB *db, CHANNEL_DB_MAPPED_FUNCTION *f, void *env) { CHANNEL_DB *p; // Assumes null terminated list. Adjust for circular lists if that's what you're using for (p = db; p; p = p-&gt;next) { int rtn = f(p, env); if (rtn != 0) return rtn; } return 0; } </code></pre> <p>The function can do anything you like and accumulate results into a record provided through the <code>void</code> pointer <code>env</code>. In particular it can do whatever you might have done with the returned list of integers. Of course this is less flexible than having the return value.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload