|
Declare an Array
#467319
07/26/17 09:22
07/26/17 09:22
|
Joined: Dec 2013
Posts: 14
oligodar
OP
Newbie
|
OP
Newbie
Joined: Dec 2013
Posts: 14
|
void main(){
int howManyItems = 10;
int myArray[howManyItems];
return;
}
Hi, compiler complains about an error in line 4. Whats the problem? I am not allowed to declare an Array this way? Thank you a lot
Last edited by oligodar; 07/26/17 09:39.
|
|
|
Re: Declare an Array
[Re: Smon]
#470035
12/20/17 11:18
12/20/17 11:18
|
Joined: Aug 2017
Posts: 102 Spain
Brax
Member
|
Member
Joined: Aug 2017
Posts: 102
Spain
|
Just remove the initial '*':
myArray[index].structmember = somevalue;
If you want to 'quickdelete' items in an array use a struct member for valid items and assign 0 to them, fi:
myArray[index].activeitem = 0;
If you want to be more precise and memory efficient, then you'll have to create a standard pointer list. That is, you'll have to add a next element struct member and whenever you delete an item, iterate through the list and assign the next element members.
Use the solution you like the most.
Last edited by brax; 12/20/17 11:22.
|
|
|
Re: Declare an Array
[Re: jcl]
#470049
12/20/17 16:44
12/20/17 16:44
|
Joined: Dec 2014
Posts: 206 Germany
Smon
Member
|
Member
Joined: Dec 2014
Posts: 206
Germany
|
I narrowed the error down.
It seems to have something to do with the static declaration I'm using. I didn't think this is important:
static mystruct *myArray = (mystruct*)malloc(howManyItems*sizeof(mystruct));
If I remove "static", the script runs fine apart from that it's now storing ridiculous numbers in the array and I don't know where these numbers are coming from.
Is the array dynamically expanded by doing
howManyItems++;
?
Last edited by sdh309795gaas; 12/20/17 16:46.
|
|
|
Re: Declare an Array
[Re: Smon]
#470051
12/20/17 17:00
12/20/17 17:00
|
Joined: Dec 2014
Posts: 206 Germany
Smon
Member
|
Member
Joined: Dec 2014
Posts: 206
Germany
|
Okay okay, I was quite naive about dynamic arrays in C. I noticed that after a little looking around on stackoverflow.com
Seems like I must either master pointers or stick with a static array.
The whole point of making the array dynamic was that I'm fearing to run out of stack memory further down the road. Is it sufficient to declare the array as a pointer and make it rather big to prevent this?
Last edited by sdh309795gaas; 12/20/17 17:01.
|
|
|
|