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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer minus minus?

Status
Not open for further replies.

Naghmeh67

Programmer
Dec 17, 2007
1
IR
Hi,

I have a question :

Is it possible to move back to the previous element when we are using pointers? like this p--; ?

Thank you,
Naghmeh
 
I think it might be worth mentioning that you need to ensure that you know the extents of the range of your pointer.

Usually the pointer points to a chunk of allocated space (either from an array or from the results of a malloc or similar call)

Your pointer probably points to somewhere in this space.

If you don't have some control over how far back you decrement your pointer, you could be pointing to space outside the allocated space.

If you were to then dereference (read from or write to anything pointed to by) the pointer then your program will probably crash.

In my experience, it's usually better to use arrays and indexes wherever possible instead of pointers because it makes range cehecking much easier.

You can ensure very easily that your index never drops below zero but how would you do the same with a pointer when all you know is the address that it points to?

With C strings we usually terminate with a null character '\0' but there is not really an equivilant for the start of a string.



Trojan.
 
ya it is possible to change the pointer using any arithmetic operation.but real reason behind this is whats your pointer type.
there are two type of pointer.
1. constant pointer
2. variable pointer
so if your pointer is of type variable than you can change its value using any arithmetic operation as you mention above,but if your pointer type is of constant,you can not change it value using arithmetic operation.compiler will give you compilation error.

so the exact answer depend on your pointer type.
example
---------------------------------------------------------

constant type::>>
when you pass array to any function than that pointer type in function is constant type.
----------------------------------------------------------
variable type::>>
any pointer which you declare and assign it value explicitly is of type variable

int *p;
int k;
p=&k;
this is variable type pointer,you can change its value
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top