On 2010-10-14, Steve555 <> wrote:
> myStructArray = (MyStruct*)malloc(1024 * sizeof(MyStruct*))
> for(long i=0; i<1024; i++){
> myStructArray[i] = malloc(sizeof(MyStruct));
> }
This can't be correct. Not seeing the declaration of myStructArray, I
can't be sure what's wrong with it, but it should be either:
myStruct *myStructArray;
myStruct init_values = { 0, 3, 21 }; /* or whatever */
myStructArray = malloc(1024 * sizeof(MyStruct));
for (int i = 0; i < 1024; ++i) {
myStructArray[i] = init_values;
}
or
myStruct **myStructArray;
myStruct init_values = { 0, 3, 21 }; /* or whatever */
myStructArray = malloc(1024 * sizeof(MyStruct *));
for (int i = 0; i < 1024; ++i) {
myStructArray[i] = malloc(sizeof(MyStruct));
*myStructArray[i] = init_values;
}
Usually, in C, you'd do the first. You're thinking like a C++ programmer,
and that's led you to two mistakes:
1. You're trying to allocate all the items separately, because you're
thinking of allocation/new as where the constructor happens. There's
no constructor! Just populate the items directly. Each element of
the array should, usually, be a myStruct, not a pointer.
2. You're casting the return from malloc. Don't do that; it's bad style
in C. (In C++, there are perhaps sound reasons for void * not to
automatically convert; in C, there aren't, so it converts automatically.
Casting pointer conversions like this just hides bugs.)
-s
--
Copyright 2010, all wrongs reversed. Peter Seebach /
usenet-
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.