okay, this is probably really simple, but i looked all over the site about pointers, arrays, and memory allocation, but some explanations are a bit too complex for me. So… could someone explain to me why d[i] are pointing to different things in the below code?
typedef struct data_t {
int ival;
char *sval;
} data_t;
void f1(data_t **d);
int main()
{
data_t *d;
d = new data_t[500];
for (int i=0; i<500; i++)
{
d[i].ival= i+1;
d[i].sval="$";
}
f1(&d);
}
void f1(data_t **d)
{
for (int i=0; i<500; i++)
{
d[i]->ival=i+1;
d[i]->sval="$";
}
}
though what i need to do is fill in each of the 500 elements of the array such that the integer field ‘ival’ has the values 1-500 for array indexes 0-499, and the string field ‘sval’ contains the string “$1” – “$500” for array indexes 0-499. in the function call.
also: is
d = new data_t[500]
all i need to allocate memory for a 500 element array of structures?
just trying to figure out why it works in the for loop in main, but not in the function call… looking at the debugger the pointers are pointing at something way wrong…
“It works” in
mainbecaused[i]is the same as*(d + i). In your functionf1,dis a pointer to a pointer, so you need to say(*d)[i].ivaletc. (What you wrote,d[i], is advancing the pointer to the pointer byisteps and then tries to dereference that, which is the wrong way round.)Then again, since you’re in C++, you should probably just have passed the pointer as a reference:
Or actually, since you’re never changing the original
ditself, only what it points to , you can even pass it by value:Or rather, you should probably use a
std::vector<data_t>and not use any pointers at all. (Also, you shouldn’t typedef your class definition ofdata_t.)