Re: printing a pointer's value
From: Lawrence Kirby (lknews_at_netactive.co.uk)
Date: 11/11/04
- Next message: Eric Sosman: "Re: printing a pointer's value"
- Previous message: dandelion: "Re: printing a pointer's value"
- In reply to: weaselboy1976: "printing a pointer's value"
- Next in thread: Eric Sosman: "Re: printing a pointer's value"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 11 Nov 2004 15:49:54 +0000
On Thu, 11 Nov 2004 07:13:14 -0800, weaselboy1976 wrote:
> Hello
>
> How can I print a pointer's value directly (without assigning the
> value to another variable)? For example:
You need to make a clear distinction between the value of a pointer and
the thing it is pointing at.
> #include <stdio.h>
>
> int main()
> {
> int *zp;
Here you have defined zp as a pointer to an int. As yet the value of the
pointer hasn't been set - it doesn't point at anything.
> *zp = 10;
*zp tries to dereference zp i.e. access what zp is pointing at. But zp
isn't pointing at anything so this operation is invalid. You need to
create an int for zp to point at. A simple way is to define an int
variable and set it to point at that e.g.
int i;
int *zp = &i;
*zp = 10; /* i is now set to 10 */
> printf ("value = |%n|\n", *zp);
Use %d to convert an int, %n does something very different.
printf ("value = |%d|\n", *zp);
> return 0;
> }
> }
You have an extra } here
> This code core dumps. Why? How can I accomplish this?
C doesn't magically allocate things for pointers to point at, it
is up to you to do this. In the code above there isn't any advantage
to using *zp over i directly, but there are other cases where
pointers are useful/necessary, e.g. for passing to other functions,
dynamic datastructures and so on.
Lawrence
- Next message: Eric Sosman: "Re: printing a pointer's value"
- Previous message: dandelion: "Re: printing a pointer's value"
- In reply to: weaselboy1976: "printing a pointer's value"
- Next in thread: Eric Sosman: "Re: printing a pointer's value"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|