While passing the array to a function, shouldn't it be the same array which is passed?

Hello friends,

I'm new to c/c++, so please forgive me if this is something stupid.
I'm trying to simulate gets() functionality and got a doubt here.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
char* xgets(char* p)
{
    char* arr = p;
    int i = 0;
    for (i=0; (i==0)? true : *(arr+i-1)!='\n'; i++)
    {
        *(arr+i) = getchar();
    }
    *(arr+i-1)='\0';
    return arr;

}
int main()
{
    char s[100];
    char* p=s;
    char* x = xgets(p);
    cout<<&p<<endl;
    cout<<&x<<endl;
    puts(x);
    puts(s);
}


Here &x and &p prints different addresses. Why is it so?
Arrays are passed by reference, which means the address of the array is passed to the function. But why is it here that we have two addresses which means we have two different arrays at the end of the job?
Last edited on
Because &x is the address of the pointer, not the address the pointer points to. Try this:
1
2
 cout<<(int)p<<endl;
    cout<<(int)x<<endl;


Oh and is there a specific reason you are doing C stuff in C++?
May I know what (int)p does?
I got some integer value. What does it signify?
(int) p means roughly "Ignore what I declared p as and pretend it is an int". The keyword is "typecast" here. p is already a pointer, and you want to know the address p points to, not the address where p is stored. That is the numerical value of p, which you get by casting it to an int.
thanks hanst99, got it.
By the way anybody can suggest a good book to learn c++
If you already know the basics (datatypes, functions, pointers) you could try Stroustrups "The C++ Programming Language". It isn't really a good introductionary book if you are completely new to programming, but if you at least got your basics covered, the book will teach you the rest you need to know (about the language that is, how to apply your knowledge about programming techniques is something that comes from experience, not from reading textbooks), and afterwards will serve you well as a language reference. If it is beginner books you are searching for, I am afraid I can't serve you with any in the english language. But you can use the tutorial on this site (see documentation) for that.
Last edited on
Thanks,
I know the basics. I can very well follow OOP concepts and data structures in C++ since I have worked almost 2 yrs in JAVA. But this pointer related things is what is eating my head off :(

I'll give a try on Stroustrup and also Herb Schildt when I win the battle against pointers :)
Topic archived. No new replies allowed.