Вы находитесь на странице: 1из 4

C Programming: Pointers and Arrays

Pointers

When you declare a variable in C, you are actually putting aside a portion of the computer’s
memory and labeling it with the variable name. The amount of memory that is used depends
on the type of the variable: an int is 4 bytes (32 bits), a char is 1 byte, a double is 8 bytes.
The location in memory is the memory address of the variable.

For example, the declaration:


int x;
results in 4 bytes of memory being put aside for an integer:
x

4 bytes

When you assign to the variable, you are storing a value in the memory at that address. For
example,
x = 5;
results in:
x

4 bytes

You can query for the address of a variable by using the ampersand (&) operator:
For example, to print the address of x in decimal form as an unsigned integer:
printf(“The address of x is %u”, &x);
Usually, memory addresses are printed in hexadecimal form:
printf(“The address of x is %x”, &x);

Suppose we want a variable y to hold the address of x. We can indicate that the variable y
holds a memory address of an int by declaring y as a pointer to an int.
int *y = &x;

Now, if we print the value of y, we can see that it is equal to the address of x:
printf(“The value of y is %x”, y);

:Note that y is itself a variable (whose type is ‘pointer to an int’) and is stored at a particular
location in memory, so you can print out the address of y too:

printf(“The address of y is %x”, &y);

You can declare multiple pointers on the same line, but you must remember to have a * for
each variable:
char *y, *z, *w;

1
Apart from its use in declaring pointers, the * symbol is also used as a dereferencing
operator. The dereferencing operator is used to examine the value of a variable pointed to
by a pointer.

For example, the expression *y means “the variable pointed to by y”.


Hence, the statement:
printf(“The value of the variable pointed to by y is %d”,
*y);

Will result in the following output:


The value of the variable pointed to by y is 5

To test your understanding of pointers, consider the following code fragment:

double x, y, w, z;
double *p1, *p2;

x = 5.0;
y = 6.0;
p1 = &x;
p2 = &y;

z = x+y ;
*p2 = *p1;
w = x+y;

p2 = p1;
(*p2)++;
(*p1)++;

After execution of this code, what are the values of x, y, w, z, p1, p2, *p1, and *p2?

Aside: We won’t look at this now, but it is worth knowing that in C, you can have pointers to
functions in addition to pointers to variables.

Passing pointers to functions

You can pass a pointer as a parameter to a function. In this case, what you are doing is
passing the address of a variable to a function. This means that the value of the variable may
be changed inside the function. Passing the address of a variable to a function is called
passing by reference. Passing the value of a variable to a function is called passing by value.
We can illustrate this with a simple example:

int myfunction(int param1, int* param2)


{
param1 = 1 ;
*param2 = 2;
}

2
int main()
{
int x = 5, y = 6;
int *pY = &y ;

printf("x=%d, y=%d", x, y);


myfunction(x, pY) ;
printf("x=%d, y=%d", x, y);
}

Running this code will cause the following to be printed to the console :
x=5, y=6
x=5, y=2

Arrays

As you already know, an array is a collection of items of the same data type. For example,
the following are all array declarations:

int ages[30]; // an array of integers


char str[20]; // an array of characters
double grades[30]; // an array of doubles
int* ptrs[38]; // an array of pointers to ints

You can refer to a particular element in the array by using the indexing operator. Valid
indices go from 0 to the length of the array -1. For example, the following sets the value of
the variable at index 3 to 69.
age[3] = 69;

When indexing into the array, you must be sure not to access elements before the beginning
of after the end of the array. C, unlike Java, does not automatically keep track of the length
of an array and so you usually want to keep a separate variable with the array size.

Array initialization

Arrays can be initialized at the time of declaration. When an array is initialized at the time of
declaration, it is not necessary to specify its size as the compiler can determine this
automatically. For example, the following are all valid array declarations:

int ages1[4] = {5, 28, 9, 20};


int ages2[] = {5, 28, 9, 20};
char letters1[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
char letters2[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};

If you do not initialize the array at the time of declaring it, the only way to assign values to all
locations in the array is to use a loop.

3
int evenNumbers[5];
for (int i=0; i<5; i++){
evenNumbers[i] = 2*(i+1);
}

In C, a string is simply a null-terminated array of characters. A string can be initialized at


the time of declaration by specifying a string literal using enclosed in double quotes. For
example, the statements below both all create valid strings:

char str1[7] = {‘A’, ‘s’, ‘h’, ‘e’, ‘s’, ‘i’, ‘\0’};


char str2[7] = “Ashesi”;
char str3[] = “Ashesi”;

Note that when you initialize a string with a string literal, the null terminator is automatically
added.

The relationship between arrays and pointers

The elements in an array are stored in contiguous locations in memory, and the name of the
array is a pointer to the first element in the array (i.e., the element at index 0).

2 4 6 8 10

evenNumbers

So, both statements below will print out the address of the first element of the array arr:
printf(“The array starts at address %x”, arr);
printf(“The array starts at address %x”, &arr[0]);

What will the following do?

char greeting[] = “hello!”;


char *greeting2, *greeting3;

printf(“%s \n”, greeting);


greeting2 = greeting;
greeting2[1] = ‘u’;
printf(“%s \n”, greeting2);
greeting3 = &greeting[1];
greeting3[0] = ‘a’;
printf(“%s \n”, greeting3);
printf(“%s \n”, greeting);

Вам также может понравиться