Re: printing a pointer's value

From: Lawrence Kirby (lknews_at_netactive.co.uk)
Date: 11/11/04


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



Relevant Pages

  • Re: Memory Structure Pointer Problems
    ... typedef struct sta { ... char* name; ... int num_cmpnds; ... A pointer to a struct cmp is almost ...
    (comp.lang.c)
  • Re: C# - getting binary data from .lib
    ... Use Marshal.AllocHGlobal to allocate the memory and pass this IntPtr to the ... int retCode = create(id, scale, ptrImage); ... You now control the pointer returned. ...
    (microsoft.public.dotnet.framework.interop)
  • Re: Another spinoza challenge
    ... You should test against the int type's limits: ... typedef struct complex ... a pointer to an integer ... A macro is preferable because it is replaced by inline code, ...
    (comp.lang.c)
  • Re: C# - getting binary data from .lib
    ... int create(int id, int scale, unsigned char *image); ... unsigned char* ptrImage = NULL; ... // Read through entire pointer byte by byte and put into managed array ...
    (microsoft.public.dotnet.framework.interop)
  • Re: C# - getting binary data from .lib
    ... then there is a problem with the ptrImage ... int retCode = create(id, scale, ptrImage); ... You now control the pointer returned. ...
    (microsoft.public.dotnet.framework.interop)