简体   繁体   中英

C++ Arrays of Pointers

I've been tasked to create an array of pointers to floats with a typedef. This is my code:

typedef float fArray[3];

fArray fArr[3] = {{1.0, 2.0, 3.0}};
fArray* fArrptr[3];

for (int i = 0; i < 3; i++){
    fArrptr[i] = &fArr[i];
}

for (int i = 0; i < 3; i++) {
  cout << (fArrptr + i) << endl;
}

From what I'm understanding it's doing is for fArrptr, it's going through each element of the array and making it point to the 'equivalent element' in fArr. The problem is when I'm trying to output what I'm wanting is 1.0, 2.0, 3.0 but instead, I'm just getting the addresses, regardless of what I do.

Am I misunderstanding what is happening?

Yes you are seriously misunderstanding.

typedef float fArray[3];

This is typedef for an array of floats, not what you were asked to do, but fine.

fArray fArr[3] = {{1.0, 2.0, 3.0}};

This is an array of fArray . But fArray is already an array, so this is an array of an array. A 2D array in other words. That's why you needed to use {{ when you initialised it.

And similarly this

fArray* fArrptr[3];

is an array of pointers to an array of floats (not an array of pointers to floats).

After these errors there's not much point going further with the code.

Here's how you create an array of pointers to floats using a typedef

typedef float* fPtrArray[3];
fPtrArray array_of_pointers;

Here's how you might initialise it

float array_of_floats[3] = { 1.0, 2.0, 3.0 };
for (int i = 0; i < 3; ++i)
    array_of_pointers[i] = &array_of_floats[i];

And here's how you might print it out

for (int i = 0; i < 3; ++i)
    cout << *array_of_pointers[i] << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM