*initialized = pointers

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Adek336

*initialized = pointers

Post by Adek336 »

Hello all! How can I make a poitner point at a variable runtime? In gcc. For some variables I do like this

long x;
void *xptr = x;
long *the_important_pointer;

...
the_important_pointer = xptr;
...

but it doesn´t work with structs.

Thanx in advance,
Adrian.
Jamethiel

RE:*initialized = pointers

Post by Jamethiel »

Umm... What you posted shouldn't work, either.

If you compiled that with -Wall, you got a message about converting an integer to a pointer without a cast, right?

Try:

struct foo {
   int bar;
   int baz;
};

void main(void)
{
    struct foo quux;
    struct foo *huh;

    huh = &quux;

    quux.bar = -1;
    quux.baz = -2;

    huh->bar = 0;
    huh->bax = 1;

    printf("%d, %d.\n", quux.bar, quux.baz);
}

This should print "0, 1".

It should compile cleanly with -Wall as well (always use -Wall with gcc).

The unary & operator is for explicitly taking the address of something.

Hope this helps.

--Jamethiel
Adek336

RE:*initialized = pointers

Post by Adek336 »

it works:))) earlier I tried ptr = @var without success now i have ptr = &var and it works :))

2 more questions:

what is foo (foobar?) and why is it so popular?

what is the differrence between & and &&?

Thanx and cheers,
Adrian.
mikeleany

RE:*initialized = pointers

Post by mikeleany »

Let me guess: you just switched over to C from Pascal?

&&(binary operator) - logical and (e.g. if (condition1 && condition2))
&(binary operator) - bitwise and (e.g. newbits = bits & otherbits)
&(unary operator) - address of (e.g. ptr = &var)

If you want to know about foo, bar and foobar, check out http://www.nue.org/foldoc/foldoc.cgi?foo
Adek336

RE:*initialized = pointers

Post by Adek336 »

thanx! I used to program pascal, but I changed to C-- for a yr and now im into C.

Adrian
Post Reply