Help with an Array of struct
Quote:
> Someone can say me if this code is correct ?
> When I try to execute this code, the program give
> an access violation.
> But I don't see where is wrong.
> struct Files **aRecord;
> .....
> int load( struct Files *rec[])
> {
> int i, iCont;
> int NumRows;
> .....
> rec = (struct Files **)malloc(NumRows*sizeof(struct Files **)+1);
> for(i=0;i<10;i++)
> {
> rec[i] = (struct Files *)malloc(sizeof(struct Files)+1);
> (*rec)[i].id = 1;
> Temp = "test1";
> (*rec)[i].szNome = strdup(Temp.c_str());
> Temp = "test2";
> (*rec)[i].szPath = strdup(Temp.c_str());
> .....
> }
> return(10);
> }
> main(..)
> {
> .....
> aRecord=(struct Files **)malloc(sizeof(struct Files *)+1);
> i=load(aRecord);
> .....
> }
the problem is you're passing aRecord as a parameter to load() and
expecting it to come back with the new value. parameters in c don't
work like that.
whenever you pass an object into a function, and you want the object to
come back with a changed value, you must pass a pointer to the object.
otherwise, only the _local copy_ of the object within the function gets
modified.
you have several options for fixing your program:
1. pass a pointer to aRecord to load(), and modify load() to work
with this additional level of pointer (struct Files ***).
2. since aRecord is already a global variable, why bother passing it
into load() at all? just use aRecord directly within load().
3. instead of passing aRecord as a parameter to load(), have load()
return a struct Files **. example:
struct Files **load()
{
struct Files **rec;
....
rec = malloc(NumRows*sizeof(struct Files *));
....
return rec;
}
main(..)
{
.....
aRecord = load();
.....
}
of course you'll have to find another way to return the record count if
you do it this way.
other comments:
get rid of the malloc in main(). you don't need it.
why is that +1 in the malloc calls?
don't cast malloc's return value. if you're #including <stdlib.h>,
which you should, you don't need the cast, and in fact it's dangerous
to do the cast.
in load(), the malloc call should be for NumRows*sizeof(struct Files *),
not NumRows*sizeof(struct Files **).
---
John Gordon "No Silicon Heaven? Preposterous! Where would