简体   繁体   中英

I have an array of pointers. How to correctly assign a value to the locations each element of the array points to?

I have this code declaring an array of pointers and assigning value of 5 to the location that the first pointer in the array points to:

int *p[10];
*p[0]=5;

However, this is showing an EXC_BAD_ACCESS error. I tried

int **p = new int *[10];
*p[0]=5;

But this is giving the same error. How do I assign a value to the location pointed by an element of my array of pointers? Thank you.

Before dereferencing the first pointer in the array, you need to initialize it to point to a valid memory location. For example:

int *p[10];
p[0] = new int;
*p[0] = 5;

Note that manual memory allocation at such level is almost certainly not what you want to use , except as a learning exercise, or as part of implementation of a larger structure. If you in fact want to an array of 10 integers, and access parts of it through a pointer, you can do it like this:

int array[10];             // allocate room for ten integers
array[0] = 5;              // initialize the first one
int *first = &array[0];    // get a pointer to the first one
assert(*first == 5);       // work with the pointer

If you do need an array of pointers, look into std::unique_ptr and std::shared_ptr to make sure they do not leak data in case of exceptions, early returns or forgotten delete .

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