Acessing Array elements with pointer

Hi,
I dont seem to understand why I am not able to acess array elements properly.

Here is a part of the code

string A[100];
string* Astr;
Astr=A;
int cnt=0;
cout<<(cnt+5)<<" "<<(cnt+4); // I get 5 and 4 which is fine

but
cout<<*(Astr+cnt+5)<<" "<<*(Astr+cnt+4); //Nothing gets printed


Can I not acess low index element after acessing the higher index, My array A is already initialized.If I print a single element in a loop it works


There is no problem with the code.

First you should assign the values to string array to get display.

Second array index starts from '0' not from 1.
If your array size is 100 then you have to use 0 to 99 as index numbers like that pointers also

*(Astr+cnt+5) will give you 6th element and
*(Astr+cnt+4) will give you 5th element.
Last edited on
@ above

You are right with the elements starting from 0, That is fine with me and my string array is initialized after reading values from a file. I just put the part of code where I had problem.
Last edited on
@mike99

Why do you want to do this with a string? You can use the at function to do this.

Normally the pointer is of a type of the data being held in the array - for example an array of ints would use a ptr to int. This is so the compiler can figure out how big each element is, so it can do the memory arithmetic properly. You have a ptr to string - how big is that? I mean it is of unknown size, don't use the sizeof operator.

If you want to do the C approach, use a char array. Make the ptr, a ptr to char.

HTH
Topic archived. No new replies allowed.