Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C, pointers, basic problem

Name: Anonymous 2006-05-20 14:45

Here is my code, just learning more about pointers:
include<stdio.h>
main()
 {
int x, *ptr_x;
int y, *ptr_y;
int z, *ptr_z;
x=64;
y=128;
z=256;
puts("This is a program used to display information on pointers:\n");
printf("x=%d and the pointer is %p\ny=%d and the pointer is %p\nz=%d and the pointer is %p\n",x,y,z,ptr_x,ptr_y,ptr_z);
return 0;
 }

And the output:
This is a program used to display information on pointers:

x=64 and the pointer is 0x80
y=256 and the pointer is 0x8fe07604
z=0 and the pointer is 0x1

Name: Anonymous 2006-05-20 18:29

Ummm

The pointers were uninitialized.  Sure, they have values, that just happens to be garbage that existed in memory when it began.

Pointers point to locations in memory, right?  I assume you want ptr_x to point to the memory location of variable x, likewise with ptr_y and y, and ptr_z with z.

To do this you do:

ptr_x = &x;
ptr_y = &y;
ptr_z = &z;

the unary & operator before a variable returns the reference (aka memory address) of said variable.

Now ptr_x, ptr_y, and ptr_z should equal the memory locations of variables x, y, and z.

You can "dereference" a pointer by putting a * before it.  So *x_ptr doesn't return x_ptr -- it returns the value of the variable that x_ptr points to (in this case, x).  So you can rewrite the corrected version (with the order that >>4 specified) of your printf statement with just the pointers and their dereference:

printf("x=%d and the pointer is %p\ny=%d and the pointer is %p\nz=%d and the pointer is %p\n", *x_ptr, x_ptr, *y_ptr, y_ptr, *z_ptr, z_ptr);

Likewise, this line:

*x_ptr = 65;

will set the variable x to 65.  But

x_ptr = 65;

will set the memory address (technically it's an offset, but let's not worry about that for now) of x_ptr to 65 and will probably yield unexpected results.  This is one way to introduce memory leaks.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List