
pointers within an array of structures
Quote:
>Hello
>I have a structure similar to the following
>typedef struct _player{
> int Total
> int *History;
>}PlayerStats;
>Of course there is really more in it than just *History and Total, but I
>edited for brevity. I have a multi-dimensional array of these such as:
>PlayerStats PStats[2][2][2];
>The problem is I want to use malloc on History so that it can be
>dynamically allocated. I have malloc set up like so:
>*PStats[0][0][0].History = malloc((sizeof(int) *
>PStats[0][0][0].Total));
Remove the leading *. PStats is a (multidimensional) array of
structs. PStats[0][0][0] is one particular struct in the array.
PStats[0][0][0].History is a variable within that particular struct.
It is a pointer to int and is the variable you want to set with the
value returned by malloc. You could also reduce the double
parentheses at each end of the malloc parameter list to a single
parenthesis.
Quote:
>But the program crashes. I really am not to sure of how to access a
>pointer within a mulit-dimensional struture array, so is my code wrong,
>or is this just impossible? I guess if I HAVE to I could just make
>History into a really big array, but I would prefer to only use the
>memory if needed and not have limitations on the size of History.
You can access each element in the array History points to by
PStats[0][0][0].History[some_index_value]. You can put that
expression on the left side of an assignment statement to initialize a
particular element or you could put it anywhere else an int variable
is acceptable to access the current value of the element. Do remember
that none of the elements in the integer array are initialized until
you do so. Accessing them before initializing them will retrieve
garbage values.
Quote:
<<Remove the del for email>>