1

suppose that I have a pointer called P with float type which is points to some values. I want to creat another pointer called Ptr to go through where the P is pointing to and return the last element. How Can I do that?

this is what I tried until now...

float *p;
float *ptr;
for(int i=0; i< sizeof p; i++){
    ptr++;
   return &ptr;
}

is that correct? sorry that my question is basic.

6
  • Do you mean "pointer to another pointer" or do you mean "pointer that points to the same data as another pointer"? Commented Oct 31, 2013 at 12:50
  • 1
    sizeof p will give you the size of your pointer on your machine. If you want an array, you will need the length too, or a mark for the end of the array (and iterate until you encounter that mark). You can't measure the size of an array using it's header and sizeof. Commented Oct 31, 2013 at 12:50
  • 2
    Just stop. There is not a single meaningful line of code here. Please stop using pointers. It's not necessary in C++ for you right now. Use std::string, std::vector and such containers. Commented Oct 31, 2013 at 12:50
  • 1
    If you want to learn C++, web tutorials and asking basic questions on SO is not the way to go. Pick up one of our recommended texts instead. Commented Oct 31, 2013 at 12:50
  • if *p points to an array/vector just iterate that Commented Oct 31, 2013 at 12:50

2 Answers 2

2

A pointer-to-pointer-to-float is declared and initialized as such:

float** ptr = &p;
Sign up to request clarification or add additional context in comments.

1 Comment

I was really confused for a second by your use of "&" in your text as you don't talk about the address-operator there :D
-1

Maybe what you try to do is this:

size_t sizeArr = N;
float *p = new float[sizeArr];
float **ptr = &p;
for(int i=0; i< sizeArr-1; i++){
    (*ptr)++;
}
return (**ptr)

...
delete[] p; //careful with this one, since there is another pointer to the same memory

where sizeArr is the length of the array to which p is pointing

UPDATE

Do not use malloc in C++ unless it is really necessary (as suggested in comments)

26 Comments

what will it return at the end?
@user2758510 At the end, ptr will point to the last element in the array (but be careful because it is pointer to pointer...)
I want it to return the last element. how to do that?
-1: Teaching an obvious newbie to use malloc in C++ is just poor form.
@john dibling: what do you mean? a newbie should not try to learn from others?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.