Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Arrays of pointers

Status
Not open for further replies.

Jon1234

IS-IT--Management
Oct 16, 2002
3
GB
I'm new to programming with C++, so this is fairly confusing. I'm trying to make an array of pointers, and it's not going real well.

I have an array of characters around 500,000 elements in size. I'm trying to make an array of pointers that then points to each of those different elements.

Take for example the string "abcdefg". I'm trying to construct a pointer array that would essentially point to each letter individually and allow me to print out the string like this:

a
ab
abc
abcd
abcde
abcdef
abcdefg

Here's what I was trying, and it doesn't seem to work:

for (int i = 0; i < strlen(strArray); i++, ptr++)
ptr = &strArray;

Any help would be greatly appreciated.

-Jon
 
Well, I think I'm pretty dumb. I realized what I was doing wrong.

Rather than &quot;char *arr;&quot; for my array, I should have been created a doubple pointer &quot;char **arr;&quot; instead.

Thanks.

-Jon
 
Hi,
what you are finding is impossible or has not sense.

A pointer &quot;points&quot; at the begining of an area or the beg.
plus an offset. What you need is just 1 pointer, and
an array of int (the lens)

for( i=1 ...
printf( &quot;%*.*s\n&quot;, i,i,string ); // or string,i,i ?

bye
 
It's not impossible.

Here I have an array of 500,000 elements, arr1. I have an array of pointers, arr2.

-----
char arr1[500000],
**arr2;

... //populate arr1

arr2 = new char * [500000];

for (int i = 0; i < 500000; i++)
arr2 = &arr1;
-----

That does what I want. That populates arr2 full of pointers to the different elements in arr1. I'm sure there are other, better ways of doing it. However, that's what I've come up with for the time being.

-Jon

 
The obvious question is why in the world would you want an array of chars and an array of pointers? The only time that I'd use an array of pointers is when I am dealing with a singlton class that keeps track of where all of the instantiated items of it's type is, or when I am using Runtime polymorphism and dynamic dispatch.

Also, the dynamic allocation of memory is a very usefull tool, but it also has the potential for a lot of errors, so using it in this case may not be a good idea. What is problem that you are attempting to solve with this char array and array of char pointer pointers?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top