[SOLVED] (C) How do you store objects on the fly?

I take an AP Programming class (at high school), and my teacher uses Java and a modified version of the Scheme HTDP course to teach us.
I love Python for its simple effectiveness, and I love C for its power.
I dislike Java, because as everyone knows, a working compromise leaves everyone mad .
That said, I just finished my "space invaders" project in Java. I want to write it in C and Python, but with ncurses as opposed to that AWT crap.
The python isn't really a problem, but...
Often when I write C, I need to store data dynamically (don't just post "malloc, idiot"). In C++, the vector object is great way to do this. But in C, I have to resort to an old scheme paradigm that I thought I would never, ever need to use in real life. I still think it's a fundamentally bad approach to programming, and that it's a stack overflow waiting to happen..
Take a look, and if you can, please give suggestions on how I may modify my "hacked-out" version of an array;
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long int num;
struct list {
num first;
struct list* rest;
void add(struct list* obj, num val)
if (obj->rest == NULL) {
obj->rest = malloc(sizeof(list));
obj->rest->first = val;
} else {
add(obj->rest, val);
void print(struct list* obj)
if (&obj->first != NULL) {
printf("> %d\n", obj->first);
print(obj->rest);
int main(void)
struct list* tree = malloc(sizeof(list));
tree->first = 10;
add(tree, 9);
add(tree, 8);
add(tree, 7);
print(tree);
free(tree);
return 0;
Notes;
> I use "num" so that there won't be any negative numbers while I deal with ufo/aup positions on the screen.
> "add()" inserts a "num" to the end of the list.
> "print()" prints out the whole list.
> I am not very comfortable using recursion this way. I don't think it's very safe, I just don't know any better...
This is the output this file produces;
> 10
> 9
> 8
> 7
Last thing (I swear). These are sample functions in my actual vadorz.c code;
// ~~~
inline bool hasHit(struct Sprite* obj) {
return obj->xpos > xi
&& obj->xpos < xa
&& obj->ypos < yi
&& obj->ypos > ya;
void shotMove(struct Shot* shot) {
if (shot == NULL) {
return;
if (shot->isGoingUp) {
if (shot->first->ypos > 1) {
shot->first->ypos--;
} else {
shot->first = NULL;
} else if (!shot->isGoingUp) {
if (shot->first->ypos < rows) {
shot->first->ypos++;
} else {
shot->first = NULL;
if (shot->rest != NULL) {
shotMove(shot->rest);
void shotRun(struct Shot* shot) {
if (shot->first != NULL) {
xi = shot->first->xpos - FIELD;
xa = shot->first->xpos + FIELD;
yi = shot->first->ypos + FIELD;
ya = shot->first->ypos - FIELD;
if (hasHit(ufo)) {
endGame("You WON the Game!");
} else if (hasHit(aup)) {
endGame("Well. You failed.");
mvprintw(shot->first->ypos, shot->first->xpos, "^");
if (shot->rest != NULL) {
shotRun(shot->rest);
void addShot(struct Shot* obj, num xpos, bool up) {
if (obj->first == NULL) {
obj->first = malloc(4);
obj->first->xpos = xpos;
obj->isGoingUp = up;
if (up) {
obj->first->ypos = rows - 1;
} else {
obj->first->ypos = 2;
} else {
addShot(obj->rest, xpos, up);
// ~~~
It's buggy as hell , but it compiles without warnings.
Last edited by vkumar (2008-10-25 19:24:50)

You really need to read a good book on data structures. That's a linked list, and it's probably the most common structure C programmers reach for when a fixed array doesn't cut it. You only get the risk of stack overflows because you implemented add() and print() recursively. Here are iterative implementations (off the top of my head, so they may not work right):
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long int num;
struct list {
/* Use traditional names */
num first;
struct list* rest;
void add(struct list* obj, num val)
/* Iterate, don't recurse */
while ( obj->rest != NULL ) {
obj = obj->rest;
obj->rest = malloc(sizeof(list));
if ( obj->rest == NULL )
exit(1);
obj->rest->first = val;
void print(struct list* obj)
for ( ; obj == NULL; obj = obj->rest )
printf("> %d\n", obj->first);
int main(void)
struct list* tree = malloc(sizeof(list));
tree->first = 10;
add(tree, 9);
add(tree, 8);
add(tree, 7);
print(tree);
free(tree);
return 0;
EDIT: Read this. It should answer any other questions you have.
Last edited by skymt (2008-10-25 15:15:32)

Similar Messages

  • Help!! How do you keep objects in the same order in a 20 page doc when inserting a new object?

    I am creating a catalog of pictures only, as objects.
    They are organized alphabetically, 4 images per page as a 2x2 grid, for 20 pages.
    I want to insert a NEW object (image) in the middle of these 20 pages, and want all the objects after it to shift over one spot to make room.
    How do I get the objects after the inserted ones to shift, as text would if you inserted more text in the middle of a paragraph?
    I can't figure out how do do that (without just putting the images in a text box and in-line, but then I lose all the spacing controls)...
    Thank you!
    Lawrence

    ID ships with a free Image Catalog script in the sample scripts. You don't need to buy one.
    And that isn't going to do what you want, exactly. You'd have to re-run the script each time you add an image to make a new file, and you don't get to set the sort order yourself.

  • How do you declare objects in the master database

    I am trying to register our CLR assembly as an unsafe assembly without having to make the database trustworthy.  Since making the database is_trustworthy_on = 1 is not a best practice, and would cause some of our customers (and our development process)
    a little bit of grief.
    I have read a ton about it but am still having trouble.
    The reason the assembly is 'Unsafe' is because it is calling the TimeZoneInfo class to convert between timezones, since we are not yet on UTC dates.  We plan to in the future but that's a big project.
    We are also not using the 'SQLCLR' but rather have written our own class library and just have a project reference to it, which works just the same, but we have found to be better for the C# programmers.
    I am playing with signing the assembly using an SNK file and have figured out what I need to do, including 1) creating a master key, 2) creating an asymmetric key using the same SNK file that signed the assembly, 3) creating a login for the asymmetric key,
    and 4) granting unsafe assembly to the login.
    When I do all that with straight SQL, it actually works!  But I am having trouble fitting this into our SSDT world.
    Should I create a separate SSDT project for items #1 through #4 above, and reference it, and check 'Include composite objects' in our publishing options?  As stated in this blog post though, I'm terrified of messing up the master database, and I'm not
    excited about the overhead of another project, a 2nd dacpac, etc.
    http://blogs.msdn.com/b/ssdt/archive/2012/06/26/composite-projects-and-schema-compare.aspx
    Since we do use a common set of deployment options in a deployment tool we wrote, which does set the 'block on data loss' to false, and the 'drop objects not in source' to true, b/c we drop tables all the time during the course of refactoring, etc. 
    I don't want to drop anything in master though, and I don't want to have to publish it separately if we didn't have to. 
    I suppose I could just have some dynamic SQL in a pre-deployment script that takes care of the master database, but I was trying to do it the 'right' way, in a declarative style, but struggling.
    So, in short, what's the recommended approach for getting an 'unsafe' CLR assembly into an SSDT project?
    The error that started all this was:
    CREATE ASSEMBLY for assembly *** failed because assembly *** is not authorized for PERMISSION_SET = UNSAFE. 
    The assembly is authorized when either of the following is true:
    the database owner (DBO) has UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on;
    or
    the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission.
    Also, would a certificate be better than an asymmetric key?  I'm not entirely sure of the difference just yet to be honest.
    Thanks,
    Ryan

    After much fighting with this, figured something out as a workaround, and thought I'd share it.
    First, I'm pretty certain the SSDT declarative way for these master objects just doesn't work yet.
    My workaround was to make a pre-deployment script (that runs when we create new databases, as well as for the current release), that takes care of the security items needed to support a signed CLR assembly with unsafe permissions.
    One issue we were running into was when it came to creating the asymmetric key, there are 4 ways to do so, and we didn't want to depend on a hard-coded/absolute file path.  The 4 ways are "From file", "from external file", "from
    assembly", or "from provider".  I still don't 100% understand the from provider way, but ultimately we are actually using the from assembly way, with a little trick/hack I did that allows us to not have to use the 'from file' way and to
    reference a hard-coded path on someone's C:\ drive.  I really really didn't want to do that b/c we create local dev databases all the time and not everyone has the same paths setup.  Also, our databases are deployed on our servers as well as remote-hosted-customer
    servers, and up until now, the database release has not needed file system access.  Even the CLR itself is created using assembly_bits, which is awesome.
    So I thought of something...
    What if I had a simple/temporary assembly, which I create from assembly_bits, use to import the public key from, through the create asymmetric key from assembly command, and then drop as if it never existed?
    Well...it works!
    Here is my current prototype of a pre-deployment script, which I'll go through and cleanup more, but thought I'd share.  I also want to document how I created the temporary assembly_bits in case anyone ever wants or needs to know, even though they really
    shouldn't.  But it should make them feel better.  Basically I just created did this to get them:
    1 - Created a C# Class Library project in the solution.
    2 - Added our .SNK to that project and removed the 'Class1.cs' that it created by default
    3 - Signed that class library with the .SNK
    4 - Added a project reference to that class library from the main database solution.
    5 - Generated a deployment script (but didn't run it) and grabbed the create assembly statement (copy/paste)
    6 - Deleted the temporary project
    7 - Pasted the code I had copy/pasted into the pre-deployment script
    Note that the objects do apparently need to go into MASTER, so at the end of the pre deployment script, I switch back to the automatic [$(DatabaseName)] after first having done USE master.
    Hope this helps someone.  Finally got it!
    BTW - The other way we almost used was to introduce a SqlCmdVariable of $StrongNameKeyFilePath but that would have been a hassle for people to set whenever they got a new machine, etc.
    Thanks,
    Ryan
    PRINT '**************************************************************************'
    PRINT 'Pre\SetupMasterDatabaseKeysAndLoginsIfNecessary.sql'
    PRINT '**************************************************************************'
    PRINT '************************************************************************************'
    PRINT 'If they do not already exist, create the database master key, as well as the asymmetric'
    PRINT 'key, from the Strong-Named File (.SNK) which signed the CLR assembly.  Finally, also'
    PRINT 'create a login from that asymmetric key and grant it the UNSAFE ASSEMBLY permission.'
    PRINT 'This is all necessary b/c the CLR currently has to be referenced for UNSAFE permissions'
    PRINT 'in order to access the TimeZoneInfo class.  This code and these objects can be removed'
    PRINT 'if the system is ever updated to use all UTC dates and no longer requires the TimeZoneInfo class.'
    PRINT '************************************************************************************'
    USE master
    PRINT N'Creating Temporary Assembly [Wits.Database.AsymmetricKeyInitialization]...'
    CREATE ASSEMBLY [Wits.Database.AsymmetricKeyInitialization]
        AUTHORIZATION [dbo]
        FROM 0x4D5BlahBlahBlah;
    IF NOT EXISTS (SELECT 1 FROM sys.symmetric_keys WHERE name LIKE '%DatabaseMasterKey%')
        BEGIN
            PRINT 'Creating Master Key...'
            CREATE MASTER KEY
                ENCRYPTION BY PASSWORD = 'I Removed This Part For This Post'
        END
    IF NOT EXISTS (SELECT 1 FROM sys.asymmetric_keys WHERE name = 'ClrExtensionAsymmetricKey')
        BEGIN
            PRINT 'Creating Asymmetric Key from strong-named file...'
            CREATE ASYMMETRIC KEY [ClrExtensionAsymmetricKey]
                FROM ASSEMBLY [Wits.Database.AsymmetricKeyInitialization]
        END
    IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE type_desc = 'ASYMMETRIC_KEY_MAPPED_LOGIN' AND name = 'ClrExtensionLogin')
        BEGIN
            PRINT 'Creating Login from Asymmetric Key...'
            CREATE LOGIN [ClrExtensionLogin] FROM ASYMMETRIC KEY [ClrExtensionAsymmetricKey]
            PRINT 'Granting Permissions to Login created from Asymmetric Key...'
            GRANT UNSAFE ASSEMBLY TO ClrExtensionLogin
        END
    PRINT N'Dropping Temporary Assembly [Wits.Database.AsymmetricKeyInitialization]...'
    DROP ASSEMBLY [Wits.Database.AsymmetricKeyInitialization]
    USE [$(DatabaseName)]

  • In acrobat  8 how do you ungroup objects?  The ungroup icon is grey and unusable.

    I used Acrobat 8 to convert pdf to a pdf form.  The fields were made by the acrobat 8 program.  On the form there is a set of yes / no questions with radio buttons.  All of the "no" buttons are in one group and all of the "yes" are in another group.  I would like to ungroup the objects then group them correctly.  When I highlight the group, I can not use the ungroup icon (on the tool bar) as it is  grey.
    Thanks.

      I am a novice at Acrobat. All of the fields have different names.  Still I can not use the ungroup or group icons

  • HT4847 How do you store apps in icloud

    How do you store apps in the Icloud??

    By either restoring your iCloud backup, which will restore all data, settings, apps and other purchased media contained in the backup, or by redownloading them from the app store as discussed here: http://support.apple.com/kb/ht2519 (which will restore the app, but not any app data).

  • HT5467 how do you change back to the south african store from the american store on your settings??

    how do you change back to the south african store from the american store on your settings??

    Settings > iTunes & App Stores > Apple ID: > View Apple ID > Country/Region...change here.

  • How do you created object level security in BI for roles.

    How do you created object level security in BI for roles.  For example if I want users to only execute reports in BI for a particular "object" report how would I do that.
    Thanks.

    Hi Maritza,
    Can you be more specific.
    If you are looking for BI Security concept, check this presentation:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/1b439590-0201-0010-ea8e-cba686f21f06
    Regards,
    Zaheer

  • How do you recoup software from the app store after a crash?

    How do you recoup software from the app store after a crash? It's not like the old days when you bought software on CDs.

    Mac App Store: Frequently Asked Questions (FAQ) - http://support.apple.com/kb/HT4461

  • How would you store a primitive type?

    Hello
    How would you store a primitive type in a Collection such as a List?
    Thanks
    Bobby

    <face grin=evil> myList.add(int.class); </face>

  • How do you store books

    How do you store books on iPads?

    Books from where, and I'm not sure what you mean by store (?).  Most ebooks have digital rights management on them which tie them to the store's own apps/ereaders, so ibooks from Apple can only be read in the iBooks app, and ebooks from Amazon can only be read in their Kindle apps and Kindle ereaders. You can download ibooks from Apple directly in the iBooks app via the Store button at the top left of the bookshelf in the app, and similarly other abook apps generally allow you to download purchases from their store directly in them. The iBooks app also supports DRM-free epub books (e.g. books from project Gutenberg etc) which you can either use 'open in' on Safari to copy them to iBooks, or you can download them on your computer, add to its iTunes (File > Add To Library) and then sync to the iBooks app via the iPad device's Books tab.
    You can copy ibooks/epubs/PDFs from the iBooks app to your computer's iTunes via File > Transfer Purchases for backup and future re-syncing.

  • How Do You Store Your Movie Masters?

    Hi all,
    I'm curious, how do you store your Movie Masters? Let's say you filmed an important Family event from a camcorder with a hard drive. You imported the footage into you mac and edited it in iMovie or Final Cut Pro or other app.
    Then what?
    Do you make a DVD?
    Do you save a DVD image file on the computer?
    Do you export a .mov or other format file?
    Do you delete the DV original files because they are so massive?
    Do you save/delete the iMovie or FCP master original footage?
    When do you delete the camcorder hard drive original (when you need the space)?
    What other approaches do you do?
    Which is the Master?
    How do you back up your movie?
    Thanks in advance for your opinions.

    Great question. I think the issue of backup is a important one, and one I always worry about since I have a lot of video footage that is irreplaceable.
    For back-up, it is helpful to define the risk you are trying to protect from.
    For example,
    1) risk of corruption in iMovie --> I might use Time Machine (but I do not because I have not had the issue)
    2) risk of hard drive failure --> I use SuperDuper! nightly
    3) Risk of theft or fire --> offsite backup
    Here is what I do...
    1) I back up my boot disk with SuperDuper automatically to alternate external partitions every other night so I always have two bootable systems. One is less than one day old, and one is less than two days old.
    2) I back up my original video files. For my Motion JPEG, VHS-->AIC, DV, and 8MM to DV, the EVENT is the copy I back up. For my AVCHD high def video, I back up the archive of the AVCHD, but I am not currently backing up the Event files, because I would need from 4 to 8 TB to back up these events depending on whether I made one copy or two.
    3) I use CrashPlan for my offsite backup. It costs less than $4 per month, and I seeded the initial backup to an external drive to minimize having to transfer video files over the Internet. I currently have 1.2TB of data backed up to CrashPlan, which includes my entire boot drive, and the files described in #2.
    4) All of the above is automated, so I don't have to think about it too much. If I have to manually do stuff, I tend to get behind.
    You have to consider the value of total multiple redundancy vs. the likelihood that 2 or three unlikely events would all happen at once. For example, CrashPlan could lose my data. My hard disk could fail. I could lose everything in a fire. But it is unlikely that they would all happen at once, except in nuclear war, in which case, who cares?
    I am considering adding Time Machine backup and some off-site backup of the Event files into the mix, but for now I am satisfied.

  • How do you delete items from the reading list?

    How do you delete items from the reading list?

    I'm trying to mark your reply as "solved my problem", but I can't see where to mark it. I tried to mark it in the email that came to me with your answer, but it went to a screen that said NOT FOUND. Help?

  • How to print/store in file the ref cursor in pl/sql block ?

    How to print/store in file the ref cursor in pl/sql block ?.

    How to print/store in file the ref cursor in pl/sql block ?.You question is quite confusing?
    So, i'm providing link in this manner.
    For RefCursor,
    http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php
    http://www.oracle.com/technology/oramag/code/tips2003/042003.html
    For UTL_FILE,
    http://www.morganslibrary.org/reference/utl_file.html
    Regards.
    Satyaki De.
    Updated with new morgan library link.
    Edited by: Satyaki_De on Feb 24, 2010 9:03 PM

  • How do you purge/compress/shrink the iPhoto11 folder/file size?

    How do you purge/compress/shrink the iPhoto11 folder/file size?
    I have been using iPhoto since iLife'05 and have always upgraded with each iteration of iLife. Without exception, I had just recently upgraded to iPhoto'11 when iLife'11 came out. Because I have used iPhoto to store all my photos and videos taken over the last 5 years or so, my iPhoto folder/file has become bigger and bigger over time and so I moved it to an external hard-drive. My main iPhoto'11 folder/file has 14,367 photos, 995 videos and is indicated to be 83 GB by iPhoto'11. But "Get Info" in Finder reports a whopping 130 GB.
    I started to think that this is getting a little crazy and I had wanted to better manage my photo collection, so I decided to "divide and conquer" this gigantic iPhoto'11 folder/file into several smaller, more manageable sized ones. So I made a duplicate copy of this gigantic iPhoto'11 folder/file onto another external hard-drive, fire-up iPhoto'11 again to delete away almost 80% of the photos and 90% of the videos. Now, my "slimmed-down" iPhoto folder/file has 3,000 photos, 75 videos and is indicated to be 6.8 GB by iPhoto'11. But despite the new "slimmed-down" status, the "Get Info" in Finder reports a still very huge 44 GB. Where did all those bulk come from? I have emptied both the iPhoto'11 Trash Can and Mac OS X Trash Can and these steps did not seemed to change anything at all.
    Therefore, I wanted to see what the "Get Info" in Finder will report if I were to delete 99.99% of the photos and video to leave just one (1) photo in iPhoto'11? Guess what is the result? My "One Photo experimental" iPhoto folder/file has 1 photo, 0 videos and is indicated to be 2 MB by iPhoto'11 yet the "Get Info" in Finder reports a mysterious 36.3 GB. There must be something hiding inside!
    Help! What can I do?

    I went on to try trashing away some of the folders and files inside and found that I could actually do it quite neatly if I go by the year which the photos are taken. After a lot of trial and error working on duplicate copy of my iPhoto '11 library, I am able to do away with all the clutter within the library and still open it normally.
    Now my 44GB obese iPhoto'11 library has been slimmed down to just a little over 7 GB (5 GB as reported by iPhoto'11) and I am just comfortable dealing with 2 GB of "don't-know-what-info" of clutter within the library.
    Remember my "One Photo Experimental" iPhoto'11 library that was 36.3 GB? I managed to bring it down to the realistic 22 MB size. This size is still double that of a brand new iPhoto'11 library I created to import 1 photo. However, it sure beat having 36.3 GB of clutter.
    So, now what I am gonna do is to "divide and conquer" the duplicate copies of my iPhoto'11 library into smaller sized ones according to their year. But I think I'll still keep the original bloated, gigantic 130 GB intact and continue to feed it with photos and videos until maybe it becomes 1 TB! Yikes!
    Anyway, million thanks for your tip and I really appreciate it! Have a Happy holidays!

  • How do I create an object on the fly

    Hello there,
         I was wondering if it is possible to create an object on-the-fly. For example:- I have a class called Customer which holds the name, address and phone number of a customer. While the program is running I get a new customer, Mr Brown. How can I create a new Customer object which will hold the details of Mr Brown.
    yours in anticipation
    seaview

    If I understood you right, you are thinking far too complicated.
    So, when you click a button, a new object shall be created and stored. So basically you write a listener to your button that contains a method like this:
    public void actionPerformed(ActionEvent e){
       Customer newCustomer = new Customer(textfield.getText());
       listOfCustomers.add(newCustomer);
    }Maybe what got you confused is the object's name. Remember this: variables and field names DON'T exist anymore at runtime! They are just meant to help you when programming. If you want Mr. Brown as a customer, you have to provide a field in the customer class for the name. If a field is required for the existence of an object, you usually write a custom constructor for it, which accepts an according parameter.

Maybe you are looking for

  • Java.io.File.delete worked in 1.1, 1.2, 1.3 & 1.4, but not in 5.0

    I have a logging utility I wrote originally in Java 1.0. A nightly housekeeping task runs which creates a ZIP file for the previous days log, then deletes the .log file. If I run this software with Java 5.0, the File.delete fails and the .LOG file re

  • Generate sqlscrip in sql server 2008 using c#

    i need to generate sqlscript with data in c# windows application. (when client click the button)..how to do this..

  • Processing log output for Purchase order

    Dear All, Iam getting some problem when iam creating an IDOC and checking in the Processing log for IDOC number. Actually i had created one custom idoc for Purchase order since my client need only some field and in one line for header and line item,

  • Flip Horizontal and Flip Vertical

    Hello Adobe, Bridge implements rotate 90 cw, 90 ccw, and 180. Having these functions available as a right-click / cmd-click context menu is extremely convenient. However, what about the companion flip horizontal and flip vertical operations ? This is

  • Purchase requisition material price

    Hi all My understanding is that the valuation price of a material (In my case MAP) is defaulted into the purchase requisition valuation price. I have a bit of a funny scenario here.  I have a plant WB00 (requesting plant - no stock is kept in this pl