Initialising pointers

This is a discussion on Initialising pointers within the C Programming forums, part of the General Programming Boards category; Hi, My question is this: The code int a=0; printf("%p", &a); shows on the screen the memory address of variable ...

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    2

    Initialising pointers

    Hi, My question is this:

    The code

    int a=0;
    printf("%p", &a);

    shows on the screen the memory address of variable a, so why can't I assign this value to another variable -

    int a=0;
    int x=0;
    x=&a;

    If &a gives a raw number as it does in the printf command, why can't x take the value of this number? The code works if I use *x=0, but I can't see why it needs that.

    Thanks for any help.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    > The code works if I use *x=0, but I can't see why it needs that.
    When you have a pointer, there are two things you may be interested in changing (the pointer, or what it points to).

    So with say
    x = 0;
    There is no immediate way for the compiler to figure out which you might mean.

    So we have two slightly different ways of saying things, to reflect what it is we're trying to do
    x = 0; /* modify the pointer */
    *x = 0; /* modify what the pointer points to */
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    BellA_RoSa
    Join Date
    May 2005
    Posts
    8

    pointers

    ok when saying int x = &a is like saying let the integer point to the pointer of an integer so it's not of the same type but when you say int * x . you are saying that x is a pointer to an integer so when saying *x = &a is like saying let the pointer x point to the integer a . hope that makes it clearer for you .
    Form what I've "learned" & and * are the same thing they are both used for pointers -> is also equivelent to *(&) ( I think )

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Bella_Rosa
    so when saying *x = &a is like saying let the pointer x point to the integer a
    Except you'd be wrong in the assignment.

    Code:
    int *x;
    int a;
    
    x = &a; /* assign the address of a to the pointer x */
    
    *x = &a; /* dereference x, giving you a, and assign it the address of a */
    Clearly the second one is incorrect.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    May 2005
    Posts
    28
    Quote Originally Posted by quzah
    Code:
    int *x;
    int a;
    
    x = &a; /* assign the address of a to the pointer x */
    
    *x = &a; /* dereference x, giving you a, and assign it the address of a */
    Clearly the second one is incorrect.
    The second one is lacking a cast but it is certainly not incorrect. What is incorrect about setting a variable to hold its own address? I mean, is it useful? Who knows But it is not "wrong". To say

    *x = (int)&a;

    simply means to store the address of a (as an int) into whatever x is pointing at, in the above example it is pointing at a, thus the end result would be to store the address of a as an integer in a.


    Mezzano

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    > The second one is lacking a cast but it is certainly not incorrect
    If you want to ride rough-shod all over the type system then go ahead, but you'll get no help from the compiler (or anyone else) if you've used so many casts as to make any kind of diagnostics ineffective.

    > What is incorrect about setting a variable to hold its own address?
    The fact that you can never achieve it without a cast perhaps?
    There's nothing in the standard which states that T and T* should ever have the same size, bit representation or anything else.

    You can do it via a struct if you want
    Code:
        struct footag {
            struct footag *self;
        } bar;
        bar.self = &bar;
    > I mean, is it useful?
    Well I've never found a use for such a thing.

    > But it is not "wrong"
    By that, you mean so long as it works on your current compiler, then it's just fine and dandy I suppose.
    Surely you should know by now that the "works for me" defence is no argument on this board, just like other brainless ideas like "void main", "fflush(stdin)" and other atrocities.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    May 2005
    Posts
    28
    Quote Originally Posted by Salem
    > The second one is lacking a cast but it is certainly not incorrect
    If you want to ride rough-shod all over the type system then go ahead, but you'll get no help from the compiler (or anyone else) if you've used so many casts as to make any kind of diagnostics ineffective.
    Why even have the ability to cast at all then, lets just take it out it is obviously useless.


    Quote Originally Posted by Salem
    > But it is not "wrong"
    By that, you mean so long as it works on your current compiler, then it's just fine and dandy I suppose.
    Surely you should know by now that the "works for me" defence is no argument on this board, just like other brainless ideas like "void main", "fflush(stdin)" and other atrocities.
    No it was more, it works on every compiler I have ever used. Of course if you want to assume the OP was planning on running this on some bizarre system which didn't have pointers being the natural word size of the machine, like ints generally are, then you are right. There is a difference between strict adherence to the standard and reasonable adherence. You are correct if you are in the camp of "I never write a single line of code that doesn't adhere 100% to the ISO C standard", you are also probably not writing any interesting code, even threading isn't covered in the standard so lets not talk about it either, I mean who would ever want to do that.


    Mezzano

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Ok wise guy. Let's examine the "it's ok to assign the value of an address to a variable" theory:
    Code:
    char *p, c;
    
    p = &c;
    *p = &c;
    See? Your cast wouldn't do jack. You still don't get the correct value. Or how about when the pointer size of an integer is bigger than an integer? Ah well, you know best.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    May 2005
    Posts
    207
    Hey Mezzano,

    Thanks for your help! Your idea really helped me a lot!

    mw

  10. #10
    Registered User
    Join Date
    May 2005
    Posts
    207
    quzah,

    I'm new to programming in C, and I don't understand the point you were trying to make in your last post about "casting not doing jack" in the example you showed. Could you elaborate on how your code works please?

    I understood the part about the pointer size exceeding the variable size, & that would obviously create a problem.

    Thanks for your input!

    mw

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    All it does it take some arbitrary value, and stick it in a variable. There's no reason to ever do this.

    [edit]
    The reason the cast wouldn't help you, is because the size of the pointer will be larger than the variable it's being stuck into, resulting in truncation of the variable, giving you a worthless value. It doesn't matter if you cast it, it's still going to be wrong.
    [/edit]


    Quzah.
    Last edited by quzah; 05-22-2005 at 11:40 PM.
    Hope is the first step on the road to disappointment.

  12. #12
    Registered User
    Join Date
    May 2005
    Posts
    2
    Thanks for the replies.

    I am still confused. &a just returns a simple number (which happens to be a memory address) right, so why can't I assign that number to an ordinary integer variable?

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    Because the compiler knows that that number is a pointer and that you are trying to asign it to a type which is not a pointer. Type checking is there to warn you about possible errors, if you use a cast then you're telling the compiler that you want to change the type and it will assume you know what your doing.
    Last edited by Quantum1024; 05-24-2005 at 06:50 AM.

  14. #14
    Registered User
    Join Date
    Apr 2004
    Posts
    25
    Quote Originally Posted by patch1024

    int a=0;
    int x=0;
    x=&a;

    If &a gives a raw number as it does in the printf command, why can't x take the value of this number? The code works if I use *x=0, but I can't see why it needs that.

    Thanks for any help.
    hey, pointers giving you hell as well?? yeah well your not the only one around here.

    i myself still don't have a firm grasp of it all. but what i think i do know is that pointers are used because when you have several functions etc, you don't want to keep returning some variable(s) becuase this takes up memory. so you use pointers.

    quick run down on pointers:
    the '&' ampersand. when couple with a variable like '&b'. this gives us the address of b.

    the '*' or otherwise known as dereferencing. if we were to write *a. then the '*' gives us access or allows us to change whatever *a is pointing to.

    so if you put these two together like so:
    a = &b //this assigns the address of b to a.
    then later you call a function you use *a to gain access to b. and b could equal to some other number 4. but once *a changes so does b.

    say if you want to add two numbers together and write a main with int x, y and the functionname, then you make it print the answer. if you do it the normal way without pointers, sure you can do it that way if you want. but after the user input, you will have to return the variable which is the sum of x, y. then your going to have to create another variable z. the function returns the value of z back into main, then you can either make it equal something else (in this case 'ans') or you can print it like so: printf("%d", mfunction(x,y)); e.g. sorry if you try to run it, i'm not sure why it's running twice.

    Code:
    int mfunction(int x, int y)
    {
        int z;
        
        printf("enter number x: ");
        scanf(" %d", &x);
        printf("enter number y: ");
        scanf(" %d", &y);
        
        z = x + y;
        
        return z;
    }
    
    
    main()
    {
        int x, y, ans;
        
        mfunction(x,y);
        ans = mfunction(x,y);
        printf("%d", ans);
        
        return 0;
    }
    ok now we'll try with pointers it'll be about the same but with less variables

    Code:
    #include <stdio.h>
    
    void mfunction(int *x, int *y)
    {
          
        printf("enter number x: ");
        scanf(" %d", x);
        printf("enter number y: ");
        scanf(" %d", y);
                    
    }
    
    
    main()
    {
        int x, y, ans;
        
        mfunction(&x,&y);
        ans = x+y;
        printf("%d", ans);
        
        return 0;
    }
    hope this helps.. sorry if it's not what you want and if i've said any crap please correct me!

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    [Please excuse the bump.]
    Quote Originally Posted by Mezzano
    No it was more, it works on every compiler I have ever used. Of course if you want to assume the OP was planning on running this on some bizarre system which didn't have pointers being the natural word size of the machine, like ints generally are, then you are right.
    Like Windows or Linux (on 64-bit platforms -- see below)? Or like DOS from days past? Oh, those bizarre PCs.

    http://www.intel.com/cd/ids/develope...664.htm?page=2:
    Pointers are not Integers: It is common for some developers to treat pointers and integers (especially long integers) as having the same size when writing 32-bit code. For example:
    Code:
    unsigned int pVal = (unsigned int)pointerVar;
    Code similar to that shown above will not work on a 64-bit operating system, since the value of the 64-bit pointer may be truncated to fit into the 32-bit integer. Whether or not truncation will happen depends on the operating system:
    • Windows: long and int remain 32-bit in length, and special new data types are defined for 64-bit integers.
    • Linux: long becomes 64-bits in size while int remains 32-bits in size on the 64-bit versions of Linux.
    http://cboard.cprogramming.com/showthread.php?p=402165
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Variable pointers and function pointers
    By Luciferek in forum C++ Programming
    Replies: 11
    Last Post: 08-02-2008, 02:04 AM
  2. Using pointers to pointers
    By steve1_rm in forum C Programming
    Replies: 18
    Last Post: 05-29-2008, 05:59 AM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  4. Staticly Bound Member Function Pointers
    By Polymorphic OOP in forum C++ Programming
    Replies: 29
    Last Post: 11-28-2002, 12:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21