简体   繁体   中英

How to create an array of pointers without using vector

I saw that an array of pointers can be created using vector, however, I don't want that. Is the example below a way to create a pointer to int array?

#include <iostream>
using namespace std;

int main() {
    int* arr[4];
    for (int i=0; i<4; ++i) {
        cout<<endl<<arr[i];
    }
}

This makes a pointer to int array and it displays the memory address of each index in the array. Now I have few questions. Is it a proper way to create a pointer to int array without a vector? Also, if I want to initialize a value inside each memory address in the given example, how is it done? And lastly why is &arr equal to arr ?

While &arr and just plain arr may both give you the same address, they are both very different.

With &arr you get a pointer to the array, and the type of it is (in your case) int* (*)[4] .

When you use arr it decays to a pointer to the first element and the type is (again, in your case) int** .

Same address, but different types.


As for the array itself, it's defined fine, you have an array of four pointers to int . However, you do not initialize the contents of the array, which means that the contents is indeterminate , and using those pointers in any way (even just printing them) leads to undefined behavior .

Your proposed way doesn't make pointer to int array. Instead of that it makes a pointer to pointer to an int array. Usually the name of any array represent a pointer to it self. Or &arr[0] also represent it.

So I hope that you got the answer for why &arr equal arr .

Creating a pointer to int array

int arr[4];
int* p = arr; //pointer to int array

Initializing each element in array

(1) Using pointer arithmetic

int size = 4;
int* p = arr;
for (int i = 0; i < size; i++)
{
    *p = i; // assigning each element i
    p++; //pointing to next element 
}

(2) Using operator []

int size = 4;
for (int i = 0; i < size; i++)
{
    arr[i] = i; // assigning each element i
}

&arr gives you the address of array which starts with base address ie address of first element.

arr gives the address of first element.

hence u get same result for both

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