Similarities and differences between pointers and arrays in C
This is an example C program which demonstrates similarities and differences between pointers and arrays.
#include <stdio.h> int main () { /* x is an array of "int" of size 10. */ int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* y is a pointer to "int". */ int * y; y = x; /* Print information about y. */ printf ("Size of y = %d\n", sizeof (y)); printf ("Contents of y = %p\n", y); printf ("Address of y = %p\n", & y); printf ("*y = %d\n", *y); printf ("y[1] = %d\n", y[1]); printf ("2[y] = %d\n", 2[y]); /* Print information about x. */ printf ("Size of x = %d\n", sizeof (x)); printf ("Contents of x = %p\n", x); printf ("Address of x = %p\n", & x); printf ("*x = %d\n", *x); printf ("x[1] = %d\n", x[1]); printf ("2[x] = %d\n", 2[x]); return 0; }
The output of the example looks like this:
Size of y = 4 Contents of y = 0xbfbfe8a0 Address of y = 0xbfbfe89c *y = 1 y[1] = 2 2[y] = 3 Size of x = 40 Contents of x = 0xbfbfe8a0 Address of x = 0xbfbfe8a0 *x = 1 x[1] = 2 2[x] = 3
The sizes and addresses printed will vary for different computers.
Notice that the contents of the pointer y
and the address
of y
are different, but for the array x
they
come out the same. The size of y
is four bytes, but the
size of x
is forty bytes.
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer