pointer and variable scope concept

A

a

Hi,
func(int* p){
p = p+1;
}
main(){
int* ptr;
//assume ptr is pointing to a valid allocated array
func(ptr);
//Will ptr equal the original address value
//or equal the original address + sizeof(int)??
}
Thanks a lot
 
W

Walter Roberson

Hi,
func(int* p){
p = p+1;
}
main(){
int* ptr;
//assume ptr is pointing to a valid allocated array
func(ptr);
//Will ptr equal the original address value
//or equal the original address + sizeof(int)??
}

Inside func, p is a *copy* of the value passed in. You then increment
that copy. The original is not changed.

If you did wish to permanently increment a pointer from inside a
function, you would have to pass the -address- of the pointer in,
and use that address to increment the value stored: that way what
the function receives is a copy of the address of the pointer, and that
copy of the address can be used to manipulate what is pointed to
(i.e., the pointer itself.)
 
C

Chris Dollin

a said:
Hi,
func(int* p){
p = p+1;
}

`p` is a local variable. Changing its value doesn't do anything
to anything else.
main(){
int* ptr;
//assume ptr is pointing to a valid allocated array
func(ptr);
//Will ptr equal the original address value

Yes. The code phrase for this is "C does not have call by reference".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top