Computing.Net > Forums > Programming > Array of pointers to Structures

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Array of pointers to Structures

Reply to Message Icon

Name: Noah
Date: May 9, 2002 at 01:13:16 Pacific
Comment:

Hi,
I want to create an array of STRUCTREs which I will
read from a file. So in this file I might have a
computer structure, microwave structure, TV... I
don't
know how many there are total. Ending up I would have
an Array with different Structures and an unknown
size. I was thinking of doing the following in C.

create an array of void pointers.
When you add something to the array use realloc to
get
the size of the array correct. Then numObj-1 =
malloc'ed space for the structure. But something is
going wrong. here is some code..
declare the variable for array of pointers.
void ** Objects;

then in Add_TV: //increase array
Objects =
realloc(Objects,nObj*sizeof(Objects));
//malloc space for strutuce
Objects[nObj-1] = (TV *) malloc(sizeof(TV));
then when I try doing this
Objects[nObj-1].channel = 5;

I get an error..
Any suggestions? I'm not sure what I'm doing wrong.

Noah



Sponsored Link
Ads by Google

Response Number 1
Name: Don Arnett
Date: May 9, 2002 at 08:20:44 Pacific
Reply:

NOTE: this would be a good application for a linked list. That way you would be realloc'ing everytime you add something.

I'm not at work today and am about to leave for the rest of the day, so I don't have access to a platform for C compiling nor much time. But I have one comment:

1 - in the last line, you'll need to cast to let the compiler know what type of structure you're using

((TV*)(Objects[nObj-1])).channel = 5


BTW, I always use calloc so that the memory is zero'ed out. I'm leaving in a bit for the rest of the day. If you'd like more help with this or would like to see how to use a linked list, just email me. But I probably won't see it until tomorrow.


0

Response Number 2
Name: Noah
Date: May 9, 2002 at 12:39:44 Pacific
Reply:

Thanks for the help.
I really wasn't sure if I should be using a Link List
or not. I tend to avoid it when I can, and I thought
they really weren't used all that much. Thanks again

Noah


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


newbie Visual J++



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Array of pointers to Structures

Array of pointers www.computing.net/answers/programming/array-of-pointers/4083.html

array of pointers www.computing.net/answers/programming/array-of-pointers/5489.html

Which data structure to use? www.computing.net/answers/programming/which-data-structure-to-use/8164.html