0% found this document useful (0 votes)
12 views21 pages

Pointer C

Pointers in C are variables that store memory addresses, allowing for dynamic memory allocation and efficient data structure manipulation. They can be used to access arrays, pass variables by address to functions, and create function pointers. Understanding pointer syntax and behavior is crucial for effective programming in C.

Uploaded by

Siddhant Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

Pointer C

Pointers in C are variables that store memory addresses, allowing for dynamic memory allocation and efficient data structure manipulation. They can be used to access arrays, pass variables by address to functions, and create function pointers. Understanding pointer syntax and behavior is crucial for effective programming in C.

Uploaded by

Siddhant Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

C - Pointers

What is a Pointer?
A pointer is a variable that stores the address of a memory location. Pointers are used to store
the addresses of other variables or memory items. A pointer is extremely helpful for another
type of parameter passing, commonly referred to as pass by address. Pointers are essential for
dynamic memory allocation.

The following are some common uses for pointers:


 To access dynamic data structures such as linked lists, trees, and queues.
 To access elements of an array or members of a structure.
 To access an array of characters as a string.
 To pass the address of a variable to a function.
Declaring a pointer variable
Pointer declarations use the * operator. They follow this format:
 int n; // declaration of a variable n
 int * ptr; // declaration of a pointer, called p
In the example above, ptr is a pointer, and its type will be specifically be referred to as
"pointer to int", because it stores the address of an integer variable. We also can say its type
is: int*
The type is important. While pointers are all the same size, as they just store a memory
address, we have to know what kind of thing they are pointing to.
 double * dptr; // a pointer to a double
 char * ch; // a pointer to a character
 float * fptr; // a pointer to a float
Sometimes the notation is confusing, because different textbooks place the * differently. The
three following declarations are equivalent:
 int *ptr;
 int* ptr;
 int * ptr;
Above three of these declare the variable ptr as a pointer to an int.
Another tricky aspect of notation: Recall that we can declare multiple variables on one line
under the same type, like this:
 int x, y, z; // three variables of type int
Since the type of a "pointer-to-int" is (int *), we might ask, does this create three pointers?
 int* a, b, c;
This is not three pointers. Instead, this is one pointer and two integers. If you want to create
multiple pointers on one declaration, you must repeat the * operator each time:
 int * a, * b, * c; // three pointers-to-int
 int * a, b, c; // a is a pointer, b and c are integers.
Assigning to pointer variables
A variable with a pointer value allocates space to hold the pointer, but not to hold anything it
points to. As with any other variable in C, a pointer-valued variable will initially contain
garbage - in this case, the address of a location which may or may not contain some useful
information. A pointer variable is initialized by assigning it the address of something that
already exists. The & (address-of) operator is commonly used to accomplish this:
 int x; /* an int variable */
 int *ptr; /* a pointer to an int */
 ptr = &x; /* p now points to n */
Operators
 *ptr -- returns the value pointed to by ptr
 &x -- returns the address of variable x
Using a pointer
There are two ways to use pointer variables:
a) To get their value (a pointer) –
 int x; /* an int variable */
 int *a; /* a pointer to an int */
 int *b; /* another pointer to an int */
 a = &x; /* a now points to x */
 b = a; /* b now points to x as well */
b) In most cases, however, you will want to work with the value stored at the location
indicated. You can do this by using the * (dereference) operator:
 int x; /* Declares an integer variable named x */
 int *a; /* Declares a pointer to an integer named a */
 a = &x; /* Assigns the address of x to the pointer a; a now points to x */
 *a = 2; /* Updates the value that a points to (which is x) to 2 */
 *a = *a + *a; /* Doubles the value of x by adding it to itself; sets x to 4 */
Example:

A pointer in C is always a pointer to a particular data type:


int*, double*, char*, etc.
Integer pointer:
An integer pointer stores only the address of an integer variable.
Syntax:
int *p; // *p is the name of pointer
Example: Integer pointer
Code:
#include<stdio.h>
int main()
{
int x = 25;
int *p;
p = &x;
printf("Value of x is: %d\n",x);
printf("Value stored at pointer p is: %d\n",*p);
printf("Address of the variable x is: %x\n",&x);
printf("p points to the address = %x\n",p);
printf("Address of the pointer p = %x\n",&p);
return 0;
}
Copy
Output:
Value of x is: 25
Value stored at pointer p is: 25
Address of the variable x is: 62fe1c
p points to the address = 62fe1c
Address of the pointer p = 62fe10
Character pointer:
A character pointer stores only the address of a character variable.
Syntax:
char *p; // *p is the name of pointer
Example: Charcter pointer
Code:
#include<stdio.h>
int main()
{
char ch = 'W',*p;
p = &ch;
printf("Value of ch is: %c\n",ch);
printf("Value stored at pointer p is: %c\n",*p);
printf("Address of the variable ch is: %x\n",&ch);
printf("p points to the address = %x\n",p);
printf("Address of the pointer p = %x\n",&p);
return 0;
}
Copy
Output:
Value of ch is: W
Value stored at pointer p is: W
Address of the variable ch is: 62fe1f
p points to the address = 62fe1f
Address of the pointer p = 62fe10
Floating pointer:
An integer pointer stores only the address of an integer variable.
Syntax:
float *p; // *p is the name of pointer
Code:
#include<stdio.h>
int main()
{
float x = 125.23;
float *p;
p = &x;
printf("Value of x is: %f\n",x);
printf("Value stored at pointer p is: %f\n",*p);
printf("Address of the variable x is: %x\n",&x);
printf("p points to the address = %x\n",p);
printf("Address of the pointer p = %x\n",&p);
return 0;
}
Copy
Output:
Value of x is: 125.230003
Value stored at pointer p is: 125.230003
Address of the variable x is: 62fe1c
p points to the address = 62fe1c
Address of the pointer p = 62fe10
Printing pointers
We can print a pointer value using printf() function with the %p format specifier. Following
program prints out some pointer values:
Code:
#include <stdio.h>
#include <stdlib.h>

int n = 0; /* a global variable*/


int main(int argc, char **argv)
{
char str[6] = "Hello"; /* String variable*/
char *cptr;
cptr = str;
static int st; /* static local variable */
int at; /* automatic variable */
int *ptr; /* pointer variable */
printf("&n = %p\n", (void *) &n);
printf("&st = %p\n", (void *) &st);
printf("&at = %p\n", (void *) &at);
printf("&ptr = %p\n", (void *) &ptr);
printf("&cptr = %p\n", (void *) &cptr);
free(ptr);
return 0;
}
Copy
Output:
&n = 0000000000407030
&st = 0000000000407034
&at = 000000000062FE04
&ptr = 000000000062FDF8
&cptr = 000000000062FE08
Manipulating Pointers
In the preceding code snippet we saw, ptr was pointing to x i.e. ptr contained the address of
the location in which x is stored. The data item represented by x can be accessed by using the
unary operator *, which is also termed as the indirection operator can be used only on
pointers. Consider the following example:
int x,y,z, *ptr;
x=34;
y=67;
z=20;
printf ("x=%d , y=%d", x , y);
/* output: x=34 , y=67 */
ptr = &x; /* ptr now points to x */
y = *ptr; /* y gets the value of variable to which ptr points i.e x*/
printf ("x=%d, y=%d", x, y);
/* output: x=34 , y=34 */
z =*ptr + 1; /* z gets the value 35 */
*ptr = 0; /* x gets the value 0 */
Copy
The null pointer:
There is a special pointer called null pointer whose value is 0. You can assign 0 into a pointer:
 ptr = 0;
Null pointer is the only integer literal that can be assigned to a pointer, and arbitrary numbers
may not be assigned to them:
 int * p = 0; // Assignment of null pointer to p
 int * q;
 q = 0; // okay. null pointer again.
 int * x;
 z = 125; // [Error] invalid conversion from 'int' to 'int*'
 double * dptr;
 dptr = 10; //invalid conversion from 'int' to 'double*'
Null pointers are never valid targets, however a segmentation fault will occur if you attempt
to dereference the null pointer. In most cases, a null pointer is used to initialize pointers until
their values are known before they are used.
Pointers of the same type:
A pointer can also be assigned to another pointer of the same type:
 int * p1, * p2; // Two pointers of type int
 p1 = p2; // Assign one to the other Now they both point to the same place
A pointer to a different type is treated by C as a different type:
 int * pi; // Pointer to int
 char * pc; // Pointer to char
 double * pd; // Pointer to double
Said three pointer variables (pi, pc ,pd) are all considered to have different types:
 pi = pd; // Invalid
 pd = pc; // Invalid
 pi = pc; // Invalid

C - Pointers and functions


Pointers and functions
The C language makes extensive use of pointers, as we have seen. They can be used to
provide indirect references to primitive types, to create dynamically sized arrays, to create
instances of structs on demand, and to manipulate string data, among other things. Pointers
can also be used to create references to functions. In other words, a function pointer is a
variable that contains the address of a function.

Functions as pointers
 Memory stores the function code
 The address or start of a function is referred to as a "function pointer"
 Since function pointers do not allocate or deallocate memory, they are "different"
from other pointers
 It is possible to pass function pointers as arguments to other functions or as returns
from other functions
Why use function pointers?
 Efficiency
 Elegance
 Runtime binding
Function pointer declarations
Unlike a function declaration, a function pointer declaration wraps the function name in
parentheses and precedes it with an asterisk. Here is an example:
 int function(int x, int y); /* a function taking two int arguments and returning an int */
 int (*pointer)(int x, int y); /* a pointer to such a function */
Pointers as Arguments
By passing a pointer into a function, the function may read or change memory outside of its
activation record.
Example: Pointers and functions
In the following example, function passes the value of p and the address of q, which are used
to initialize the variables x and ptry in the function test.
Code:
#include <stdio.h>
void test( int x, int *ptry )
{
x = 200;
*ptry = 200;
return;
}
int main( void )
{
int p = 10, q = 20;
printf( "Initial value of p = %d and q = %d\n", p, q );
test( p, &q );
printf( "After passes to test function: p = %d, q = %d\n", p, q );
return 0;
}
Copy
In the said code ‘p’ remains at 10 as there is no return value form the function test, but q
change its value from 20 to 200 in the function test() as bptr holds the address of a variable q
that is stored in main function. So when we change the value of *bptr it will automatically
reflecte in the main function.
Output:
Initial value of p = 10 and q = 20
After passes to test function: p = 10, q = 200
Example: Swapping two values using pointers and functions
Code:
#include<stdio.h>
void swap (int *p, int *q) {
int temp_val;
temp_val = *p;
*p = *q;
*q = temp_val;
}

int main()
{
int x = 45;
int y = 65;
printf( "Initial value of x = %d and y = %d\n", x, y );
swap(&x, &y);
printf( "After swapping said values x = %d and y = %d\n", x, y );
return 0;
}
Copy
Output:
Initial value of x = 45 and y = 65
After swapping said values x = 65 and y = 45
Pointer as Return Value
 A pointer can also be returned by functions
 In this case, the function returns the memory address of where the value is stored
rather than the value itself
 Ensure that you do not return an address to a temporary variable in a function!
Example of Returning a Pointer:
Code: Maximum of two numbers
#include <stdio.h>

int* max(int *a, int *b)


{
if (*a > *b)
return a;
return b;
}

int main()
{
int x = 105, y = 102, *ptr;
printf("Original Numbers: x = %d, y = %d",x , y);
ptr = max(&x, &y);
printf("\nMaximum of said two numbers: %d", *ptr);
return 0;
}
Copy
Output:
Original Numbers: x = 105, y = 102
Maximum of said two numbers: 105

Arrays and Pointers


Arrays and Pointers
Pointer
 Address of a variable in memory
 Allows us to indirectly access variables
 in other words, we can talk about its address rather than its value
Arrays:
Array is a group of elements that share a common name, and that are different from one
another by their positions within the array. Under one name, a collection of elements of the
same type is stored in memory.
 can be of any data type, e.g., integer, character, long integer, float, double, etc.
 even collection of arrays
 Arrays of structure, pointer , union etc. are also allowed
Advantages:
 For ease of access to any element of an array
 Passing a group of elements to a function
How arrays are stored in memory?
An array of one-dimensional elements consists of a series of individual variables of the array
data type, each stored one after the other in the computer's memory. Each element has an
address, just as all other variables do. An array's address is its first element, which
corresponds to the first byte of memory it occupies.
Here we declare an array of seven integers like this:
int nums[7] = {54, 6, 23, 45, 32, 78, 89};
Let's assume that the first element of the array scores has the address 1200. This means that
&nums[0] would be 1000. Since an int occupies 4 bytes, the address of the second element of
the array, &nums[1] would be 1204, the address of the third element of the array, &nums[2]
would be 1208, and so on.

[0] [1] [2] [3] [4] [5] [6]

nums 54 6 23 45 32 78 89

1200 1204 1208 1212 1216 1220 1224

What about a two-dimensional array declared like this?


int nums [2][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
Visualize the said two-dimensional array as a table of rows and columns:

column

[0] [1] [2] [3]


row [0] 1 2 3 4

[1] 5 6 7 8

numbers

Array: Syntax and Declaration

Pointers and arrays in C:

Relationship between Arrays and Pointers


Following 3 for loops are equivalent:
Code:
#include <stdio.h>
#define N 5
int main() {
int i, * ptr, sum = 0;
int nums[N] = {1, 2, 3, 4, 5};
for (ptr = nums; ptr < & nums[N]; ++ptr)
sum += * ptr;
printf("Sum = %d ", sum); // Sum = 15
}
Copy
Output:
Sum = 15
Code:
#include <stdio.h>
#define N 5
int main() {
int i, * ptr, sum = 0;
int nums[N] = {1, 2, 3, 4, 5};
for(i = 0; i < N; ++i)
sum += *(nums+i);
printf("Sum = %d ", sum); // Sum = 15
}
Copy
Output:
Sum = 15
Code:
#include <stdio.h>
#define N 5
int main() {
int i, * ptr, sum = 0;
int nums[N] = {1, 2, 3, 4, 5};
ptr = nums;
for(i = 0; i < N; ++i)
sum += ptr[i];
printf("Sum = %d ", sum); // Sum = 15
}
Copy
Output:
Sum = 15
Example: Arrays and Pointers
Following example print i) array elements using the array notation and ii) by dereferencing
the array pointers:
Code:
#include <stdio.h>
int nums[] = {0, 5, 87, 32, 4, 5};
int *ptr;
int main(void)
{
int i;
ptr = &nums[0]; /* pointer to the first element of the array */
printf("Print array elements using the array notation\n");
printf("and by dereferencing the array pointers:\n");
for (i = 0; i < 6; i++)
{
printf("\nnums[%d] = %d ", i , nums[i]);
printf("\nptr + %d = %d\n",i, *(ptr + i));
}
return 0;
}
Copy
Output:
Print array elements using the array notation
and by dereferencing the array pointers:

nums[0] = 0
ptr + 0 = 0
nums[1] = 5
ptr + 1 = 5
nums[2] = 87
ptr + 2 = 87
nums[3] = 32
ptr + 3 = 32
nums[4] = 4
ptr + 4 = 4
nums[5] = 5
ptr + 5 = 5
Passing Arrays as Parameters
Code:
#include <stdio.h>
int sum( int *a, int l) {
int i, s = 0;
for(i = 0; i < l; i++)
s += a[i];
return s;
}
int main()
{
int nums[5] = {1, 2, 3, 4, 5};
int size = sizeof(nums)/sizeof(nums[0]);
printf("Sum is %d\n", sum(nums, size)); //15
return 0;
}
Copy
Output:
Sum is 15
Example: Passing a 2D Array to a Function
In the following example, a 2D array is passed as a parameter, where the second dimension is
specified and the first one is not specified:
Code:
#include <stdio.h>
void test(int N[][4])
{
int i, j;
printf("\n\nPrint the matrix within the test function:");
for (i = 0; i < 4; i++)
{
printf("\n");
for (j = 0; j < 4; j++)
printf("%d ", N[i][j]);
}
printf("\n");
}
int main()
{
int nums[4][4], i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
nums[i][j] = i;
printf("Original Matrix: ");
for (i = 0; i < 4; i++) {
printf("\n");
for (j = 0; j < 4; j++)
printf("%d ", nums[i][j]);
}
test(nums);
}
Copy
In the following example, a pointer to a 2D array is passed as a parameter, where the second
dimension is specified:
Code:
#include <stdio.h>
void test(int (*N)[4])
{
int i, j;
printf("\n\nPrint the matrix within the test function:");
for(i = 0 ; i < 4 ; i++)
{
printf("\n");
for(j = 0 ; j < 4 ; j++)
printf("%d ", N[i][j]);
}
printf("\n");
}
int main()
{
int nums[4][4], i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
nums[i][j] = i;
printf("Original Matrix: ");
for (i = 0; i < 4; i++)
{
printf("\n");
for (j = 0; j < 4; j++)
printf("%d ", nums[i][j]);
}
test(nums);
}
Copy
In the following example, a pointer to a 2D array is passed as a parameter, where the second
dimension is specified:
Code:
#include <stdio.h>
void test(int (*N)[4])
{
int i, j;
printf("\n\nPrint the matrix within the test function:");
for(i = 0 ; i < 4 ; i++)
{
printf("\n");
for(j = 0 ; j < 4 ; j++)
printf("%d ", N[i][j]);
}
printf("\n");
}
int main()
{
int nums[4][4], i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
nums[i][j] = i;
printf("Original Matrix: ");
for (i = 0; i < 4; i++)
{
printf("\n");
for (j = 0; j < 4; j++)
printf("%d ", nums[i][j]);
}
test(nums);
}
Copy
In the following example, a single pointer of a 2D array is passed as parameter:
Code:
#include <stdio.h>
void test(int *N)
{
int i, j;
printf("\n\nPrint the matrix within the test function:");
for(i = 0 ; i < 4 ; i++)
{
printf("\n");
for(j = 0 ; j < 4 ; j++)
printf("%d ", *(N+ 4*i + j));
}
printf("\n");
}
int main()
{
int nums[4][4], i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
nums[i][j] = i;
printf("Original Matrix: ");
for (i = 0; i < 4; i++)
{
printf("\n");
for (j = 0; j < 4; j++)
printf("%d ", nums[i][j]);
}
test(*nums);
}
Copy
Output of the said three programs:
Original Matrix:
0000
1111
2222
3333
Print the matrix within the test function:
0000
1111
2222
3333

You might also like