Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How &a is a pointer to a if it generates the address of a?

I'm new to programming, and at present I am learning about pointers in C.

  1. I know that pointers are the variables which contain or hold address of another variable. Today when I was more learning about it with K&R I got confused in a line which says "&a is a pointer to a" in a given function swap(&a,&b) in Page No. 80. How &a is a pointer? It is not a variable, it is the address of the variable. Am I right?
  2. I know that arguments can be passed to a function in two ways: call by value and call by reference. The caller's value of the argument is not changed in the first one, but it can be changed in the second one.

My question is I had read that if we want to change the value of the variable we have to pass the pointer to it (i.e. the location of the value we want to modify). What is meant by that? I mean, do we have to pass pointers to the function? And what is the meaning of the statement, "we have to pass the pointers to the location we want to modify".

like image 605
Yogesh Tripathi Avatar asked Dec 01 '22 18:12

Yogesh Tripathi


1 Answers

A pointer is not a variable. A pointer is a value.

A variable, in C, designates a storage location, and a value can be stored in that location. Thus, if you have a variable a declared with int a, then a is a variable in which an integer value can be stored. If you have a variable int *x, then x is a variable in which a pointer to an integer value can be stored.

The address of a storage location can be obtained using the & operator. E.g., &a is the address of the storage location designated by a, or the address of a, and can be stored in (among other things) a variable of the corresponding type. Thus you can have:

int  a = 42;  /* a is a variable of type int,  and has value 42 */
int* x = &a;  /* x is a variable of type int*, and has value &a */

Although analogies in programming are often dangerous, you might think of things like page numbers in a book. The page number of a page is not the same thing as the page, but page numbers can still be written down on pages. E.g., the table of contents page has lots of page numbers written down on it. Thus:

actual_page p = ...; /* a page structure */
page_number n = &p;  /* a page number    */
like image 57
Joshua Taylor Avatar answered Jan 05 '23 08:01

Joshua Taylor