Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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

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.

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

![]() |
newbie
|
Visual J++
|

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